@motionhub/oms 0.1.0 → 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/worker.cjs CHANGED
@@ -33,6 +33,7 @@ __export(worker_exports, {
33
33
  VOICE_ENV: () => VOICE_ENV,
34
34
  check: () => check,
35
35
  effectsTrack: () => effectsTrack,
36
+ font: () => font,
36
37
  motionWords: () => motionWords,
37
38
  pack: () => pack,
38
39
  parseCues: () => parseCues,
@@ -44,7 +45,6 @@ __export(worker_exports, {
44
45
  renderStages: () => renderStages,
45
46
  searchMotions: () => searchMotions,
46
47
  still: () => still,
47
- takeFont: () => takeFont,
48
48
  useMotion: () => useMotion,
49
49
  voice: () => voice2,
50
50
  voiceSetup: () => voiceSetup,
@@ -53,7 +53,7 @@ __export(worker_exports, {
53
53
  module.exports = __toCommonJS(worker_exports);
54
54
  var import_node_crypto7 = require("node:crypto");
55
55
  var import_promises12 = require("node:fs/promises");
56
- var import_node_os3 = require("node:os");
56
+ var import_node_os4 = require("node:os");
57
57
  var import_node_path14 = require("node:path");
58
58
 
59
59
  // ../desktop/src/main/film/film.ts
@@ -241,6 +241,7 @@ var ASSETS = [
241
241
  ".ttf",
242
242
  ".otf",
243
243
  ".mp4",
244
+ ".mov",
244
245
  ".webm",
245
246
  ".mp3",
246
247
  ".wav",
@@ -429,6 +430,8 @@ var TYPES = {
429
430
  ".ttf": "font/ttf",
430
431
  ".otf": "font/otf",
431
432
  ".mp4": "video/mp4",
433
+ // A screen recording from macOS: Chromium plays its H.264 when told it is MP4, and refuses video/quicktime in a data: URL.
434
+ ".mov": "video/mp4",
432
435
  ".webm": "video/webm",
433
436
  ".mp3": "audio/mpeg",
434
437
  ".wav": "audio/wav",
@@ -767,6 +770,7 @@ ${line.text.trim().replace(/\r?\n+/g, "\n")}
767
770
  }
768
771
 
769
772
  // ../desktop/src/main/film/capture.ts
773
+ var import_node_os = require("node:os");
770
774
  var VIDEO = [
771
775
  "-vf",
772
776
  "scale=out_color_matrix=bt709:out_range=tv,format=yuv420p",
@@ -807,6 +811,7 @@ var run2 = (ffmpeg, args) => new Promise((done, fail) => {
807
811
  child.on("error", fail);
808
812
  child.on("close", (code) => code === 0 ? done() : fail(new Error(`ffmpeg exited ${code}: ${said.trim().split("\n").slice(-3).join(" / ")}`)));
809
813
  });
814
+ var renderStages = (cores = (0, import_node_os.availableParallelism)(), free = (0, import_node_os.freemem)()) => Math.max(1, Math.min(cores, Math.floor(free / 15e8), 8));
810
815
  async function exportFrames(dir, version, file, onProgress, signal, open, ffmpeg, { output = buildDir(dir), stages = 1, resume, segmentFrames = SEGMENT_FRAMES } = {}) {
811
816
  const stage = await open(version);
812
817
  const others = [];
@@ -909,6 +914,17 @@ async function drawSegment(drawing, film, s, e, file, ffmpeg, signal, onDrawn) {
909
914
  });
910
915
  finished.catch(() => {
911
916
  });
917
+ let unlisten = () => {
918
+ };
919
+ const cancelled = new Promise((_, stop) => {
920
+ const cancel = () => stop(new Error("The export was cancelled."));
921
+ if (signal.aborted) return cancel();
922
+ signal.addEventListener("abort", cancel, { once: true });
923
+ unlisten = () => signal.removeEventListener("abort", cancel);
924
+ });
925
+ cancelled.catch(() => {
926
+ });
927
+ const unlessCancelled = (promise) => Promise.race([promise, cancelled]);
912
928
  try {
913
929
  let next = s;
914
930
  let broken = null;
@@ -918,10 +934,10 @@ async function drawSegment(drawing, film, s, e, file, ffmpeg, signal, onDrawn) {
918
934
  for (let i = first; i < e; i += drawing.length) {
919
935
  if (broken) throw broken;
920
936
  if (signal.aborted) throw new Error("The export was cancelled.");
921
- const png = await photographer.png(i / film.fps);
922
- await turn(i);
937
+ const png = await unlessCancelled(photographer.png(i / film.fps));
938
+ await unlessCancelled(turn(i));
923
939
  if (broken) throw broken;
924
- await write(encoder.stdin, png);
940
+ await unlessCancelled(write(encoder.stdin, png));
925
941
  onDrawn(i + 1 - s);
926
942
  next = i + 1;
927
943
  waiting.get(next)?.go();
@@ -946,6 +962,8 @@ async function drawSegment(drawing, film, s, e, file, ffmpeg, signal, onDrawn) {
946
962
  });
947
963
  await (0, import_promises4.rm)(file, { force: true });
948
964
  throw error;
965
+ } finally {
966
+ unlisten();
949
967
  }
950
968
  await finished;
951
969
  }
@@ -1009,13 +1027,13 @@ async function findFfmpeg() {
1009
1027
  return ffmpeg;
1010
1028
  }
1011
1029
 
1012
- // chrome.ts
1030
+ // ../desktop/src/main/film/chrome.ts
1013
1031
  var import_browsers = require("@puppeteer/browsers");
1014
1032
  var import_node_child_process4 = require("node:child_process");
1015
1033
  var import_node_crypto2 = require("node:crypto");
1016
1034
  var import_node_fs4 = require("node:fs");
1017
1035
  var import_promises5 = require("node:fs/promises");
1018
- var import_node_os = require("node:os");
1036
+ var import_node_os2 = require("node:os");
1019
1037
  var import_node_path7 = require("node:path");
1020
1038
 
1021
1039
  // ../desktop/src/shared/preview.ts
@@ -1117,8 +1135,8 @@ var inspectScript = `(() => {
1117
1135
  return { outside: [...outside.values()], unloaded: [...unloaded.values()], shown: [...shown] };
1118
1136
  })()`;
1119
1137
 
1120
- // chrome.ts
1121
- function chromeBuild(platform = process.platform, release = (0, import_node_os.release)()) {
1138
+ // ../desktop/src/main/film/chrome.ts
1139
+ function chromeBuild(platform = process.platform, release = (0, import_node_os2.release)()) {
1122
1140
  return platform === "darwin" && Number.parseInt(release, 10) < 22 ? "150.0.7871.124" : "158.0.8127.36";
1123
1141
  }
1124
1142
  var DIGESTS = {
@@ -1141,8 +1159,8 @@ var EXECUTABLE = {
1141
1159
  "win32/ia32": ["chrome-headless-shell-win32", "chrome-headless-shell.exe"],
1142
1160
  "win32/x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"]
1143
1161
  };
1144
- var PUPPETEER_CACHE = (0, import_node_path7.join)((0, import_node_os.homedir)(), ".cache", "puppeteer");
1145
- var hyperframesCache = () => (0, import_node_path7.join)(process.env.HYPERFRAMES_CACHE_DIR ? (0, import_node_path7.resolve)(process.env.HYPERFRAMES_CACHE_DIR) : (0, import_node_path7.join)((0, import_node_os.homedir)(), ".cache", "hyperframes"), "chrome");
1162
+ var PUPPETEER_CACHE = (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".cache", "puppeteer");
1163
+ var hyperframesCache = () => (0, import_node_path7.join)(process.env.HYPERFRAMES_CACHE_DIR ? (0, import_node_path7.resolve)(process.env.HYPERFRAMES_CACHE_DIR) : (0, import_node_path7.join)((0, import_node_os2.homedir)(), ".cache", "hyperframes"), "chrome");
1146
1164
  var RUNNING_WRITES = ["debug.log", "chrome_debug.log"];
1147
1165
  function filesUnder(folder, prefix = "") {
1148
1166
  const names2 = [];
@@ -1183,8 +1201,8 @@ function inCache(cacheDir, build2, digests = DIGESTS[build2] ?? [], platform = `
1183
1201
  return binary && pinned(binary, digests) ? binary : void 0;
1184
1202
  }
1185
1203
  var SYSTEM_CHROMIUM = ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
1186
- function systemChromium(paths = SYSTEM_CHROMIUM) {
1187
- for (const path of paths) {
1204
+ function systemChromium(paths2 = SYSTEM_CHROMIUM) {
1205
+ for (const path of paths2) {
1188
1206
  try {
1189
1207
  const real = (0, import_node_fs4.realpathSync)(path);
1190
1208
  const owned = (file) => {
@@ -1316,7 +1334,7 @@ var Pipe = class {
1316
1334
  else call.done(message2.result);
1317
1335
  }
1318
1336
  };
1319
- async function start(binary, profile, sandbox, driven) {
1337
+ async function start(binary, profile, sandbox, driven, gpu) {
1320
1338
  const args = [
1321
1339
  // Driven: a page's compositor draws a frame only when HeadlessExperimental.beginFrame asks for one.
1322
1340
  ...driven ? ["--deterministic-mode"] : [],
@@ -1331,10 +1349,17 @@ async function start(binary, profile, sandbox, driven) {
1331
1349
  "--force-color-profile=srgb",
1332
1350
  "--force-device-scale-factor=1",
1333
1351
  // Each frame rastered whole: rastering only what changed leaves a frame's pixels depending on the frame drawn before
1334
- // it, so frames drawn by several Chromes, or in another order, would differ.
1352
+ // it, so frames drawn by several Chromes of one path, or in another order, would differ.
1335
1353
  "--disable-partial-raster",
1336
1354
  // WebGL in software where there is no GPU, as the Studio does (stage.ts allowSoftwareWebGL).
1337
1355
  "--enable-unsafe-swiftshader",
1356
+ // On the GPU (drawPath, ADR 0022): WebGL on the machine's GPU, through ANGLE on the platform's own graphics API. A
1357
+ // GPU that Chrome blocklists is used only when OMS_RENDER_GPU=1 asks for it.
1358
+ ...gpu ? [
1359
+ "--enable-gpu",
1360
+ `--use-angle=${process.platform === "win32" ? "d3d11" : process.platform === "darwin" ? "metal" : "vulkan"}`,
1361
+ ...process.env.OMS_RENDER_GPU === "1" ? ["--ignore-gpu-blocklist"] : []
1362
+ ] : [],
1338
1363
  // Nothing leaves the machine: every name fails to resolve and every request not answered from the film goes to a
1339
1364
  // proxy that is not there.
1340
1365
  "--host-resolver-rules=MAP * ~NOTFOUND",
@@ -1348,6 +1373,8 @@ async function start(binary, profile, sandbox, driven) {
1348
1373
  printed = (printed + data.toString()).slice(-4e3);
1349
1374
  });
1350
1375
  const pipe = new Pipe(child.stdio[3], child.stdio[4]);
1376
+ child.stdio[3].on("error", (error) => pipe.close(error));
1377
+ child.stdio[4].on("error", (error) => pipe.close(error));
1351
1378
  const exited = new Promise(
1352
1379
  (_, fail) => child.once("exit", (code, signal) => {
1353
1380
  const error = new Error(`Chrome exited (${signal ?? code}) before it answered.
@@ -1361,49 +1388,117 @@ ${printed.trim()}`);
1361
1388
  return { child, pipe };
1362
1389
  }
1363
1390
  var FRAME_MS = 6e4;
1391
+ var ASLEEP_MS = 5e3;
1364
1392
  function timeout(promise, what) {
1365
1393
  let timer;
1366
1394
  return Promise.race([
1367
1395
  promise,
1368
1396
  new Promise((_, fail) => {
1369
- timer = setTimeout(() => fail(new Error(`${what} took longer than ${FRAME_MS / 1e3} s.`)), FRAME_MS);
1397
+ let spent = 0;
1398
+ let last = Date.now();
1399
+ timer = setInterval(() => {
1400
+ const now = Date.now();
1401
+ if (now - last <= ASLEEP_MS) spent += now - last;
1402
+ last = now;
1403
+ if (spent >= FRAME_MS) fail(new Error(`${what} took longer than ${FRAME_MS / 1e3} s.`));
1404
+ }, 1e3);
1370
1405
  })
1371
- ]).finally(() => clearTimeout(timer));
1406
+ ]).finally(() => clearInterval(timer));
1372
1407
  }
1373
1408
  var ORIGIN = "https://film.invalid";
1374
1409
  var drivable = (binary, platform = process.platform) => platform === "linux" && (0, import_node_path7.basename)(binary).startsWith("chrome-headless-shell");
1375
1410
  var undriven = false;
1376
- async function openChromeStage(binary, dir, output, studio2, profile) {
1377
- if (!drivable(binary) || undriven) return openIn(binary, dir, output, studio2, profile, false);
1411
+ async function openChromeStage(binary, dir, output, studio2, profile, version = 1) {
1412
+ if (!drivable(binary) || undriven) return openIn(binary, dir, output, studio2, profile, false, version);
1378
1413
  try {
1379
- return await openIn(binary, dir, output, studio2, profile, true);
1414
+ return await openIn(binary, dir, output, studio2, profile, true, version);
1380
1415
  } catch (driving) {
1381
- const stage = await openIn(binary, dir, output, studio2, `${profile}-screenshots`, false);
1416
+ const stage = await openIn(binary, dir, output, studio2, `${profile}-screenshots`, false, version);
1382
1417
  undriven = true;
1383
1418
  console.error(`oms: Chrome could not draw frames on demand here (${String(driving).split("\n")[0]}); it takes screenshots instead.`);
1384
1419
  return stage;
1385
1420
  }
1386
1421
  }
1387
- async function openIn(binary, dir, output, studio2, profile, driven) {
1422
+ var SOFTWARE = /swiftshader|llvmpipe|softpipe|basic render|software/i;
1423
+ function onGpu(env, renderer) {
1424
+ if (env === "0") return false;
1425
+ if (env === "1") return true;
1426
+ return !!renderer && !SOFTWARE.test(renderer);
1427
+ }
1428
+ var RENDERER_SCRIPT = `(() => {
1429
+ const canvas = document.createElement('canvas');
1430
+ const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
1431
+ if (!gl) return null;
1432
+ const info = gl.getExtension('WEBGL_debug_renderer_info');
1433
+ return String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER));
1434
+ })()`;
1435
+ async function gpuRenderer(binary) {
1436
+ const profile = await (0, import_promises5.mkdtemp)((0, import_node_path7.join)((0, import_node_os2.tmpdir)(), "oms-gpu-"));
1437
+ let started = null;
1438
+ try {
1439
+ const sandbox = sandboxWanted();
1440
+ const launched = await start(binary, profile, sandbox, false, true).catch((error) => sandbox ? start(binary, profile, false, false, true) : Promise.reject(error));
1441
+ started = launched;
1442
+ const { pipe } = launched;
1443
+ const { targetId } = await pipe.send("Target.createTarget", { url: "about:blank" });
1444
+ const { sessionId } = await pipe.send("Target.attachToTarget", { targetId, flatten: true });
1445
+ const reply = await timeout(
1446
+ pipe.send("Runtime.evaluate", { expression: RENDERER_SCRIPT, returnByValue: true }, sessionId),
1447
+ "Asking Chrome for its GPU"
1448
+ );
1449
+ return reply.result.value ?? null;
1450
+ } catch {
1451
+ return null;
1452
+ } finally {
1453
+ if (started) {
1454
+ const { child, pipe } = started;
1455
+ const gone = new Promise((done) => child.exitCode === null && child.signalCode === null ? child.once("exit", done) : done(null));
1456
+ const kill = setTimeout(() => child.kill("SIGKILL"), 5e3);
1457
+ void pipe.send("Browser.close").catch(() => {
1458
+ });
1459
+ await gone;
1460
+ clearTimeout(kill);
1461
+ }
1462
+ await (0, import_promises5.rm)(profile, { recursive: true, force: true, maxRetries: 5 }).catch(() => {
1463
+ });
1464
+ }
1465
+ }
1466
+ var paths = /* @__PURE__ */ new Map();
1467
+ function drawPath(binary) {
1468
+ let found = paths.get(binary);
1469
+ if (!found) {
1470
+ const env = process.env.OMS_RENDER_GPU;
1471
+ found = (async () => {
1472
+ if (env === "0") return { gpu: false, renderer: "SwiftShader" };
1473
+ const renderer = await gpuRenderer(binary);
1474
+ return onGpu(env, renderer) ? { gpu: true, renderer: renderer ?? "unknown" } : { gpu: false, renderer: "SwiftShader" };
1475
+ })();
1476
+ paths.set(binary, found);
1477
+ }
1478
+ return found;
1479
+ }
1480
+ var describePath = (path) => `${path.gpu ? "the GPU" : "the CPU"} (${path.renderer})`;
1481
+ async function openIn(binary, dir, output, studio2, profile, driven, version) {
1482
+ const path = await drawPath(binary);
1388
1483
  let sandbox = sandboxWanted();
1389
1484
  let started;
1390
1485
  try {
1391
- started = await start(binary, profile, sandbox, driven);
1486
+ started = await start(binary, profile, sandbox, driven, path.gpu);
1392
1487
  } catch (error) {
1393
1488
  if (!sandbox || process.env.OMS_CHROME_SANDBOX === "1" || !/sandbox|namespace/i.test(String(error))) throw error;
1394
1489
  sandbox = false;
1395
- started = await start(binary, profile, sandbox, driven);
1490
+ started = await start(binary, profile, sandbox, driven, path.gpu);
1396
1491
  }
1397
1492
  if (!sandbox) warnUnsandboxed();
1398
1493
  const { child, pipe } = started;
1399
1494
  const close = async () => {
1400
- await pipe.send("Browser.close").catch(() => {
1495
+ if (child.exitCode !== null || child.signalCode !== null) return;
1496
+ const gone = new Promise((done) => child.once("exit", done));
1497
+ const kill = setTimeout(() => child.kill("SIGKILL"), 5e3);
1498
+ void pipe.send("Browser.close").catch(() => {
1401
1499
  });
1402
- if (child.exitCode === null && child.signalCode === null) {
1403
- const gone = new Promise((done) => child.once("exit", done));
1404
- setTimeout(() => child.kill("SIGKILL"), 5e3).unref();
1405
- await gone;
1406
- }
1500
+ await gone;
1501
+ clearTimeout(kill);
1407
1502
  };
1408
1503
  try {
1409
1504
  const { targetId } = await pipe.send("Target.createTarget", { url: "about:blank", ...driven ? { enableBeginFrameControl: true } : {} });
@@ -1447,13 +1542,13 @@ async function openIn(binary, dir, output, studio2, profile, driven) {
1447
1542
  };
1448
1543
  const failed = () => evaluate("window.__omsError ?? null");
1449
1544
  await pipe.send("Emulation.setDeviceMetricsOverride", { width: 1920, height: 1080, deviceScaleFactor: 1, mobile: false }, sessionId);
1450
- await timeout(pipe.send("Page.navigate", { url: `${ORIGIN}/?render=1&v=1` }, sessionId), "Loading the film");
1545
+ await timeout(pipe.send("Page.navigate", { url: `${ORIGIN}/?render=1&v=${version}` }, sessionId), "Loading the film");
1451
1546
  const film = await timeout(
1452
1547
  (async () => {
1453
1548
  for (; ; ) {
1454
1549
  const error = await failed();
1455
1550
  if (error) throw new Error(error);
1456
- const info = await evaluate("window.__oms ? (({seek, ...film}) => film)(window.__oms) : null");
1551
+ const info = await evaluate("window.__oms ? (({seek, moving, ...film}) => film)(window.__oms) : null");
1457
1552
  if (info) return info;
1458
1553
  await new Promise((done) => setTimeout(done, 50));
1459
1554
  }
@@ -1477,27 +1572,50 @@ async function openIn(binary, dir, output, studio2, profile, driven) {
1477
1572
  }
1478
1573
  throw new Error("Chrome drew no frame in five begin frames.");
1479
1574
  };
1575
+ const seekTo = async (t) => {
1576
+ const moved = evaluate(seekScript(t));
1577
+ if (!driven) return moved;
1578
+ let settled = false;
1579
+ moved.then(() => settled = true, () => settled = true);
1580
+ const until = Date.now() + FRAME_MS;
1581
+ try {
1582
+ while (!settled && Date.now() < until) {
1583
+ if (await evaluate("window.__oms.moving()")) await beginFrame(false);
1584
+ else await new Promise((done) => setTimeout(done, 2));
1585
+ }
1586
+ } catch {
1587
+ }
1588
+ return moved;
1589
+ };
1480
1590
  if (driven) {
1481
1591
  await timeout(beginFrame(false), "Drawing the first frame");
1482
- const error = await timeout(evaluate(seekScript(0)), "The frame at 0 s");
1592
+ const error = await timeout(seekTo(0), "The frame at 0 s");
1483
1593
  if (error) throw new Error(error);
1484
1594
  await timeout(beginFrame(true), "Drawing the first frame");
1485
1595
  }
1486
1596
  return {
1487
1597
  film,
1488
1598
  inspect: () => timeout(evaluate(inspectScript), "Inspecting the frame"),
1489
- async png(t) {
1490
- const error = await timeout(evaluate(seekScript(t)), `The frame at ${t.toFixed(2)} s`);
1599
+ async png(t, box) {
1600
+ const error = await timeout(seekTo(t), `The frame at ${t.toFixed(2)} s`);
1491
1601
  if (error) throw new Error(error);
1492
- if (driven) return await timeout(beginFrame(true), `Photographing the frame at ${t.toFixed(2)} s`);
1493
- const shot = await timeout(
1494
- pipe.send("Page.captureScreenshot", { format: "png", optimizeForSpeed: true }, sessionId),
1495
- `Photographing the frame at ${t.toFixed(2)} s`
1496
- );
1497
- return Buffer.from(shot.data, "base64");
1602
+ if (box) await evaluate(`window.__omsMark?.(${JSON.stringify(box)})`);
1603
+ try {
1604
+ return await photograph(t);
1605
+ } finally {
1606
+ if (box) await evaluate("window.__omsMark?.(null)");
1607
+ }
1498
1608
  },
1499
1609
  close
1500
1610
  };
1611
+ async function photograph(t) {
1612
+ if (driven) return await timeout(beginFrame(true), `Photographing the frame at ${t.toFixed(2)} s`);
1613
+ const shot = await timeout(
1614
+ pipe.send("Page.captureScreenshot", { format: "png", optimizeForSpeed: true }, sessionId),
1615
+ `Photographing the frame at ${t.toFixed(2)} s`
1616
+ );
1617
+ return Buffer.from(shot.data, "base64");
1618
+ }
1501
1619
  } catch (error) {
1502
1620
  await close();
1503
1621
  throw error;
@@ -1650,11 +1768,25 @@ async function elevenLabs(setup, voice3, text, speed, io) {
1650
1768
  if (!json.audio_base64) throw new Error("ElevenLabs answered with no speech.");
1651
1769
  return { audio: Buffer.from(json.audio_base64, "base64"), words: json.alignment ? elevenLabsWords(json.alignment) : [] };
1652
1770
  }
1771
+ function miniMaxPieces(subtitles) {
1772
+ const entries = (Array.isArray(subtitles) ? subtitles : [subtitles]).flatMap((s) => s?.timestamped_words ?? []);
1773
+ const pieces = [];
1774
+ for (const e of entries) {
1775
+ const span = e.word_begin !== void 0 && e.word_end !== void 0 ? `${e.word_begin}:${e.word_end}` : void 0;
1776
+ const last = pieces[pieces.length - 1];
1777
+ if (span && last?.span === span) {
1778
+ last.end = e.time_end / 1e3;
1779
+ last.said += e.pronounce_word ?? "";
1780
+ } else pieces.push({ text: e.word, start: e.time_begin / 1e3, end: e.time_end / 1e3, said: e.pronounce_word ?? e.word, span });
1781
+ }
1782
+ return pieces;
1783
+ }
1653
1784
  function miniMaxWords(subtitles) {
1654
- const entries = (Array.isArray(subtitles) ? subtitles : [subtitles]).flatMap(
1655
- (s) => s?.timestamped_words ?? []
1656
- );
1657
- return groupWords(entries.map((e) => ({ text: e.word, start: e.time_begin / 1e3, end: e.time_end / 1e3 })));
1785
+ return groupWords(miniMaxPieces(subtitles));
1786
+ }
1787
+ function miniMaxMisread(subtitles) {
1788
+ const letters = (s) => s.toLowerCase().replace(/[^\p{L}]/gu, "");
1789
+ return miniMaxPieces(subtitles).filter((p) => p.text.trim() && !/[\p{N}%$€£¥&@#+=/]/u.test(p.text) && letters(p.text) && letters(p.said) && letters(p.text) !== letters(p.said)).map((p) => ({ written: p.text.trim(), said: p.said.trim() }));
1658
1790
  }
1659
1791
  async function miniMax(setup, voice3, text, speed, io) {
1660
1792
  const base = setup.region === "china" ? "https://api.minimaxi.com" : "https://api.minimax.io";
@@ -1678,7 +1810,7 @@ async function miniMax(setup, voice3, text, speed, io) {
1678
1810
  if (!json.data?.audio || !/^https:\/\//.test(json.data.audio)) throw new Error("MiniMax answered with no speech.");
1679
1811
  const audio = Buffer.from(await (await io.fetch(json.data.audio)).arrayBuffer());
1680
1812
  const subtitles = json.data.subtitle_file && /^https:\/\//.test(json.data.subtitle_file) ? await (await io.fetch(json.data.subtitle_file)).json() : null;
1681
- return { audio, words: subtitles ? miniMaxWords(subtitles) : [] };
1813
+ return { audio, words: subtitles ? miniMaxWords(subtitles) : [], misread: subtitles ? miniMaxMisread(subtitles) : [] };
1682
1814
  }
1683
1815
  function openAiWords(transcript) {
1684
1816
  return (transcript.words ?? []).filter((w) => w.word.trim()).map((w) => ({ text: w.word.trim(), start: round(w.start), end: round(w.end) }));
@@ -1788,7 +1920,7 @@ async function voiceFilm(dir, film, setupFor, ffmpeg, onLine = () => {
1788
1920
  await (0, import_promises6.mkdir)(folder, { recursive: true });
1789
1921
  const kept = new Set((await (0, import_promises6.readdir)(folder)).filter((file) => CLIP.test(file)));
1790
1922
  const narration = { voice: film.voice, lines: {} };
1791
- const outcome = { spoken: 0, kept: 0, characters: 0, seconds: 0 };
1923
+ const outcome = { spoken: 0, kept: 0, characters: 0, seconds: 0, misread: [] };
1792
1924
  for (const [i, line] of lines.entries()) {
1793
1925
  const key = clipKey(film.voice, setup.model, line.text);
1794
1926
  narration.lines[line.id] = key;
@@ -1808,6 +1940,7 @@ async function voiceFilm(dir, film, setupFor, ffmpeg, onLine = () => {
1808
1940
  const clip = { text: line.text, voice: film.voice, seconds, words: spoken.words.map((w) => ({ ...w, end: Math.min(w.end, seconds) })) };
1809
1941
  await (0, import_promises6.writeFile)((0, import_node_path8.join)(folder, `${key}.json`), `${JSON.stringify(clip, null, 2)}
1810
1942
  `);
1943
+ for (const m of spoken.misread ?? []) outcome.misread.push({ line: line.id, ...m });
1811
1944
  outcome.spoken++;
1812
1945
  outcome.characters += line.text.length;
1813
1946
  outcome.seconds += seconds;
@@ -1829,7 +1962,7 @@ var import_node_child_process6 = require("node:child_process");
1829
1962
  var import_node_crypto5 = require("node:crypto");
1830
1963
  var import_node_fs5 = require("node:fs");
1831
1964
  var import_promises7 = require("node:fs/promises");
1832
- var import_node_os2 = require("node:os");
1965
+ var import_node_os3 = require("node:os");
1833
1966
  var import_node_path9 = require("node:path");
1834
1967
  var TRANSCRIBERS = ["minimax", "openai", "elevenlabs"];
1835
1968
  var NETWORK2 = { fetch: (...args) => fetch(...args), WebSocket };
@@ -2060,7 +2193,7 @@ async function voiceRecording(dir, film, file, setup, ffmpeg, cache, onStep = ()
2060
2193
  if (cached2) heard = JSON.parse(await (0, import_promises7.readFile)(transcript, "utf8"));
2061
2194
  else {
2062
2195
  const seconds = await mediaSeconds(ffmpeg, file);
2063
- const work = await (0, import_promises7.mkdtemp)((0, import_node_path9.join)((0, import_node_os2.tmpdir)(), "oms-recording-"));
2196
+ const work = await (0, import_promises7.mkdtemp)((0, import_node_path9.join)((0, import_node_os3.tmpdir)(), "oms-recording-"));
2064
2197
  heard = [];
2065
2198
  try {
2066
2199
  for (let offset = 0; offset < seconds; offset += CHUNK_SECONDS) {
@@ -2332,14 +2465,24 @@ var MOST_BYTES = 1024 ** 3;
2332
2465
  var MOST_FILES = 2e4;
2333
2466
  var SKIPPED = /* @__PURE__ */ new Set([".git", "node_modules", STATE_DIR, ".DS_Store", "Thumbs.db"]);
2334
2467
  var EXPORTS = /^[^/]+\.(mp4|srt|png|oms)$/i;
2335
- async function packedFiles(dir, prefix = "") {
2468
+ async function bytesUnder(folder) {
2469
+ let total = 0;
2470
+ for (const entry of await (0, import_promises9.readdir)(folder, { withFileTypes: true })) {
2471
+ const path = (0, import_node_path11.join)(folder, entry.name);
2472
+ if (entry.isDirectory()) total += await bytesUnder(path);
2473
+ else if (entry.isFile()) total += (await (0, import_promises9.lstat)(path)).size;
2474
+ }
2475
+ return total;
2476
+ }
2477
+ async function packedFiles(dir, prefix = "", leftOut = []) {
2336
2478
  const found = [];
2337
2479
  const entries = (await (0, import_promises9.readdir)((0, import_node_path11.join)(dir, prefix), { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2338
2480
  for (const entry of entries) {
2339
2481
  const path = `${prefix}${entry.name}`;
2340
2482
  if (SKIPPED.has(entry.name) || EXPORTS.test(path)) continue;
2341
2483
  if (entry.isSymbolicLink()) throw new Error(`${path} is a link: a packed film holds the project's own files, so copy it in instead.`);
2342
- if (entry.isDirectory()) found.push(...await packedFiles(dir, `${path}/`));
2484
+ if (entry.isDirectory() && entry.name.startsWith(".")) leftOut.push({ path: `${path}/`, bytes: await bytesUnder((0, import_node_path11.join)(dir, path)) });
2485
+ else if (entry.isDirectory()) found.push(...await packedFiles(dir, `${path}/`, leftOut));
2343
2486
  else if (entry.isFile()) found.push(path);
2344
2487
  }
2345
2488
  return found;
@@ -2348,12 +2491,13 @@ function field(header, at, width, value) {
2348
2491
  header.write(typeof value === "number" ? value.toString(8).padStart(width - 1, "0") : value, at, width, "utf8");
2349
2492
  }
2350
2493
  async function packProject(dir) {
2351
- const paths = await packedFiles(dir);
2352
- if (!paths.includes("film.tsx")) throw new Error(`${dir} holds no film.tsx: name the project folder.`);
2353
- if (paths.length > MOST_FILES) throw new Error(`The project holds ${paths.length} files, more than ${MOST_FILES}.`);
2494
+ const leftOut = [];
2495
+ const paths2 = await packedFiles(dir, "", leftOut);
2496
+ if (!paths2.includes("film.tsx")) throw new Error(`${dir} holds no film.tsx: name the project folder.`);
2497
+ if (paths2.length > MOST_FILES) throw new Error(`The project holds ${paths2.length} files, more than ${MOST_FILES}.`);
2354
2498
  const blocks = [];
2355
2499
  let total = 0;
2356
- for (const path of paths) {
2500
+ for (const path of paths2) {
2357
2501
  const data = await (0, import_promises9.readFile)((0, import_node_path11.join)(dir, path));
2358
2502
  total += data.length;
2359
2503
  if (total > MOST_BYTES) throw new Error(`The project holds more than ${MOST_BYTES / 1024 ** 3} GB: leave its large media out of the folder.`);
@@ -2380,7 +2524,7 @@ async function packProject(dir) {
2380
2524
  blocks.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
2381
2525
  }
2382
2526
  blocks.push(Buffer.alloc(1024));
2383
- return { bytes: (0, import_node_zlib.gzipSync)(Buffer.concat(blocks), { level: 9 }), files: paths.length };
2527
+ return { bytes: (0, import_node_zlib.gzipSync)(Buffer.concat(blocks), { level: 9 }), files: paths2.length, leftOut };
2384
2528
  }
2385
2529
 
2386
2530
  // ../desktop/src/main/film/effects.ts
@@ -2686,15 +2830,16 @@ function wav16(samples, rate2) {
2686
2830
  return Buffer.concat([header, data]);
2687
2831
  }
2688
2832
 
2689
- // font.ts
2833
+ // ../desktop/src/main/font.ts
2690
2834
  var import_promises11 = require("node:fs/promises");
2691
2835
  var import_node_path13 = require("node:path");
2692
2836
  var TEXT = /\.(tsx|ts|jsx|js|json|md)$/i;
2693
2837
  var SKIPPED2 = /* @__PURE__ */ new Set(["node_modules", ".git", ".motion-studio", "media"]);
2694
2838
  var MOST = 3e3;
2695
- async function projectCharacters(dir) {
2839
+ async function projectCharacters(dir, sources = []) {
2696
2840
  const chars = /* @__PURE__ */ new Set();
2697
2841
  for (let c = 32; c < 127; c++) chars.add(String.fromCharCode(c));
2842
+ for (const source of sources) for (const char of source) if (char.codePointAt(0) >= 32) chars.add(char);
2698
2843
  const walk = async (at) => {
2699
2844
  for (const entry of await (0, import_promises11.readdir)(at, { withFileTypes: true }).catch(() => [])) {
2700
2845
  if (SKIPPED2.has(entry.name)) continue;
@@ -2715,30 +2860,41 @@ function faces(css) {
2715
2860
  url: /src:\s*url\(([^)]+)\)/.exec(body)?.[1] ?? ""
2716
2861
  })).filter((face) => face.url.startsWith("https://fonts.gstatic.com/"));
2717
2862
  }
2718
- function names(font) {
2863
+ function names(font2) {
2719
2864
  const found = /* @__PURE__ */ new Map();
2720
- const tables = font.readUInt16BE(4);
2865
+ const tables = font2.readUInt16BE(4);
2721
2866
  for (let i = 0; i < tables; i++) {
2722
2867
  const at = 12 + i * 16;
2723
- if (font.toString("latin1", at, at + 4) !== "name") continue;
2724
- const table = font.readUInt32BE(at + 8);
2725
- const count = font.readUInt16BE(table + 2);
2726
- const strings = table + font.readUInt16BE(table + 4);
2868
+ if (font2.toString("latin1", at, at + 4) !== "name") continue;
2869
+ const table = font2.readUInt32BE(at + 8);
2870
+ const count = font2.readUInt16BE(table + 2);
2871
+ const strings = table + font2.readUInt16BE(table + 4);
2727
2872
  for (let r = 0; r < count; r++) {
2728
2873
  const record2 = table + 6 + r * 12;
2729
- const [platform, , language, id, length, offset] = [0, 2, 4, 6, 8, 10].map((o) => font.readUInt16BE(record2 + o));
2730
- const bytes = font.subarray(strings + offset, strings + offset + length);
2874
+ const [platform, , language, id, length, offset] = [0, 2, 4, 6, 8, 10].map((o) => font2.readUInt16BE(record2 + o));
2875
+ const bytes = font2.subarray(strings + offset, strings + offset + length);
2731
2876
  const text = platform === 3 ? Buffer.from(bytes).swap16().toString("utf16le") : platform === 1 ? bytes.toString("latin1") : "";
2732
2877
  if (text && (!found.has(id) || platform === 3 && language === 1033)) found.set(id, text);
2733
2878
  }
2734
2879
  }
2735
2880
  return found;
2736
2881
  }
2882
+ function bundledSources(bundle) {
2883
+ const map = /\/\/# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)\s*$/.exec(bundle);
2884
+ if (!map) return [];
2885
+ const { sources = [], sourcesContent = [] } = JSON.parse(Buffer.from(map[1], "base64").toString("utf8"));
2886
+ return sources.flatMap((source, i) => /(^|\/)node_modules\//.test(source) || !sourcesContent[i] ? [] : [sourcesContent[i]]);
2887
+ }
2737
2888
  var slug = (family) => family.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
2738
- async function takeFont(dir, family, weights, ofl, get = (url) => fetch(url, { signal: AbortSignal.timeout(6e4) })) {
2889
+ async function takeFont(dir, family, weights, ofl, sources = [], get = (url) => fetch(url, { signal: AbortSignal.timeout(6e4) })) {
2739
2890
  if (!family.trim() || !weights.length || weights.some((w) => !Number.isInteger(w) || w < 1 || w > 1e3)) throw new Error('Name a family and weights from 1 to 1000, as --family "Noto Sans SC" --weights 400,700.');
2740
- const text = await projectCharacters(dir);
2741
- if ([...text].length > MOST) throw new Error(`The project writes ${[...text].length} different characters, more than ${MOST}: oms font cuts a face for a film's words, not a whole script.`);
2891
+ const text = await projectCharacters(dir, sources);
2892
+ const count = [...text].length;
2893
+ if (count > MOST) {
2894
+ const imported = sources.length ? count - [...await projectCharacters(dir)].length : 0;
2895
+ const theirs = imported ? `, ${imported} of them only in files it imports from outside its folder (their code and comments count too)` : "";
2896
+ throw new Error(`The film writes ${count} different characters${theirs}, more than ${MOST}: oms font cuts a face for a film's words, not a whole script.`);
2897
+ }
2742
2898
  const query = `family=${encodeURIComponent(family.trim()).replace(/%20/g, "+")}:wght@${[...new Set(weights)].sort((a, b) => a - b).join(";")}&text=${encodeURIComponent(text)}`;
2743
2899
  const response = await get(`https://fonts.googleapis.com/css2?${query}`);
2744
2900
  if (!response.ok)
@@ -2778,6 +2934,12 @@ ${terms || "The font names no licence: check its terms on fonts.google.com befor
2778
2934
  }
2779
2935
 
2780
2936
  // worker.ts
2937
+ async function font(dir, scratch, family, weights, ofl) {
2938
+ const output = (0, import_node_path14.join)(scratch, "build");
2939
+ const build2 = await buildFilmOnce(dir, output);
2940
+ if (!build2.ok) return { ...await takeFont(dir, family, weights, ofl), unbuilt: build2.errors.join("\n") };
2941
+ return takeFont(dir, family, weights, ofl, bundledSources(await (0, import_promises12.readFile)((0, import_node_path14.join)(output, `film-${build2.version}.js`), "utf8")));
2942
+ }
2781
2943
  var OFL = (0, import_node_path14.join)(__dirname, "OFL.txt");
2782
2944
  var studio = (0, import_node_path14.join)(__dirname, "resources", "preview");
2783
2945
  async function opener(dir, scratch) {
@@ -2788,7 +2950,6 @@ async function opener(dir, scratch) {
2788
2950
  const open = async () => openChromeStage(await findChrome(), dir, output, studio, (0, import_node_path14.join)(scratch, `profile-${opened++}`)).catch(async (error) => Promise.reject(await where(error)));
2789
2951
  return { build: build2, output, open, where };
2790
2952
  }
2791
- var renderStages = (cores = (0, import_node_os3.availableParallelism)(), free = (0, import_node_os3.freemem)()) => Math.max(1, Math.min(cores, Math.floor(free / 15e8), 8));
2792
2953
  async function check(dir, scratch) {
2793
2954
  const { build: build2, output, open } = await opener(dir, scratch);
2794
2955
  const review = await reviewBuild(build2, open, void 0, { bundle: (0, import_node_path14.join)(output, `film-${build2.version}.js`), dir });
@@ -2808,19 +2969,22 @@ async function check(dir, scratch) {
2808
2969
  }
2809
2970
  return review;
2810
2971
  }
2811
- var RENDERS = (0, import_node_path14.join)((0, import_node_os3.homedir)(), ".cache", "oms", "renders");
2972
+ var RENDERS = (0, import_node_path14.join)((0, import_node_os4.homedir)(), ".cache", "oms", "renders");
2812
2973
  var KEPT_MS = 7 * 24 * 36e5;
2813
2974
  async function render(dir, scratch, file, onProgress, signal) {
2814
2975
  const { build: build2, output, open } = await opener(dir, scratch);
2815
2976
  if (!build2.ok) throw new Error(build2.errors.join("\n"));
2816
2977
  const ffmpeg = await findFfmpeg();
2817
- const resume = (0, import_node_path14.join)(RENDERS, (0, import_node_crypto7.createHash)("sha256").update(await findChrome()).digest("hex").slice(0, 12));
2978
+ const binary = await findChrome();
2979
+ const path = await drawPath(binary);
2980
+ const resume = (0, import_node_path14.join)(RENDERS, (0, import_node_crypto7.createHash)("sha256").update(`${binary}\0${path.gpu ? `gpu\0${path.renderer}` : "cpu"}`).digest("hex").slice(0, 12));
2818
2981
  for (const chrome of await (0, import_promises12.readdir)(RENDERS).catch(() => []))
2819
2982
  for (const kept of await (0, import_promises12.readdir)((0, import_node_path14.join)(RENDERS, chrome)).catch(() => [])) {
2820
2983
  const at = (0, import_node_path14.join)(RENDERS, chrome, kept);
2821
2984
  if (Date.now() - (await (0, import_promises12.stat)(at)).mtimeMs > KEPT_MS) await (0, import_promises12.rm)(at, { recursive: true, force: true });
2822
2985
  }
2823
2986
  await exportFrames(dir, build2.version, file, onProgress, signal, open, ffmpeg, { output, stages: renderStages(), resume });
2987
+ return { drawnOn: describePath(path) };
2824
2988
  }
2825
2989
  var scripts = { core: (0, import_node_path14.join)(studio, "core.js"), player: (0, import_node_path14.join)(__dirname, "player.js") };
2826
2990
  async function filmOf(open) {
@@ -2833,11 +2997,11 @@ async function filmOf(open) {
2833
2997
  }
2834
2998
  async function pack(dir, out) {
2835
2999
  if (!out.toLowerCase().endsWith(OMS_EXTENSION)) throw new Error(`Name a film file ending in ${OMS_EXTENSION}.`);
2836
- const { bytes, files } = await packProject(dir);
3000
+ const { bytes, files, leftOut } = await packProject(dir);
2837
3001
  const partial = `${out}.partial`;
2838
3002
  await (0, import_promises12.writeFile)(partial, bytes);
2839
3003
  await (0, import_promises12.rename)(partial, out);
2840
- return { files, bytes: bytes.length };
3004
+ return { files, bytes: bytes.length, leftOut };
2841
3005
  }
2842
3006
  async function player(dir, scratch, out) {
2843
3007
  const { build: build2, output, open } = await opener(dir, scratch);
@@ -2916,7 +3080,7 @@ async function voice2(dir, scratch, onLine) {
2916
3080
  if (!film.voice) throw new Error('The film names no voice: give its <Film> one, as voice="minimax:Chinese (Mandarin)_News_Anchor".');
2917
3081
  return voiceFilm(dir, film, async (kind) => voiceSetup(kind), await findFfmpeg(), onLine);
2918
3082
  }
2919
- var TRANSCRIPTS = (0, import_node_path14.join)((0, import_node_os3.homedir)(), ".cache", "oms", "transcripts");
3083
+ var TRANSCRIPTS = (0, import_node_path14.join)((0, import_node_os4.homedir)(), ".cache", "oms", "transcripts");
2920
3084
  async function record(dir, scratch, file, kind, onStep) {
2921
3085
  const by = kind ?? TRANSCRIBERS.find((k) => process.env[VOICE_ENV[k].key]?.trim());
2922
3086
  if (!by) throw new Error(`A recording is transcribed by MiniMax, OpenAI or ElevenLabs, with its key in ${TRANSCRIBERS.map((k) => VOICE_ENV[k].key).join(", ")}: set one in the environment oms runs in.`);
@@ -2961,6 +3125,7 @@ async function still(dir, scratch, seconds) {
2961
3125
  VOICE_ENV,
2962
3126
  check,
2963
3127
  effectsTrack,
3128
+ font,
2964
3129
  motionWords,
2965
3130
  pack,
2966
3131
  parseCues,
@@ -2972,7 +3137,6 @@ async function still(dir, scratch, seconds) {
2972
3137
  renderStages,
2973
3138
  searchMotions,
2974
3139
  still,
2975
- takeFont,
2976
3140
  useMotion,
2977
3141
  voice,
2978
3142
  voiceSetup,