@bendyline/squisq-cli 2.8.8 → 2.8.10

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.
@@ -1,15 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  GIF_EXPORT_DEFAULTS,
4
+ lastMeaningfulFfmpegLine,
4
5
  runFfmpeg
5
- } from "./chunk-GGVASRPG.js";
6
+ } from "./chunk-Y5XKUWJ5.js";
6
7
 
7
8
  // src/api.ts
8
- import { mkdir, readFile as readFile3, writeFile } from "fs/promises";
9
- import { dirname as dirname2, resolve as resolvePath } from "path";
9
+ import { randomBytes as randomBytes2 } from "crypto";
10
+ import { mkdir as mkdir2, readFile as readFile4, rm as rm2, writeFile as writeFile2 } from "fs/promises";
11
+ import { tmpdir as tmpdir2 } from "os";
12
+ import { dirname as dirname2, join as join4, resolve as resolvePath } from "path";
10
13
  import { resolveMediaSchedule as resolveMediaSchedule2 } from "@bendyline/squisq/schemas";
11
14
  import { flattenBlocks as flattenBlocks2 } from "@bendyline/squisq/doc";
12
- import { ffmpegGifOutputArgs, generateRenderHtml } from "@bendyline/squisq-video";
15
+ import { ffmpegGifOutputArgs, frameTimeSeconds, generateRenderHtml } from "@bendyline/squisq-video";
13
16
  import { resolveDashboardDimensions, resolveDimensions } from "@bendyline/squisq-video";
14
17
  import {
15
18
  convert as formatsConvert,
@@ -132,13 +135,13 @@ function round3(n) {
132
135
  return Math.round(n * 1e3) / 1e3;
133
136
  }
134
137
  async function mixTimelineClips(ffmpegPath, usable, signal) {
135
- const { writeFile: writeFile2, readFile: readFile4, mkdir: mkdir2, rm: rm2 } = await import("fs/promises");
136
- const { join: join3 } = await import("path");
137
- const { tmpdir: tmpdir2 } = await import("os");
138
- const { randomBytes: randomBytes2 } = await import("crypto");
138
+ const { writeFile: writeFile3, readFile: readFile5, mkdir: mkdir3, rm: rm3 } = await import("fs/promises");
139
+ const { join: join5 } = await import("path");
140
+ const { tmpdir: tmpdir3 } = await import("os");
141
+ const { randomBytes: randomBytes3 } = await import("crypto");
139
142
  signal?.throwIfAborted();
140
- const workDir = join3(tmpdir2(), `squisq-audio-mix-${randomBytes2(8).toString("hex")}`);
141
- await mkdir2(workDir, { recursive: true });
143
+ const workDir = join5(tmpdir3(), `squisq-audio-mix-${randomBytes3(8).toString("hex")}`);
144
+ await mkdir3(workDir, { recursive: true });
142
145
  try {
143
146
  signal?.throwIfAborted();
144
147
  const inputs = [];
@@ -146,15 +149,15 @@ async function mixTimelineClips(ffmpegPath, usable, signal) {
146
149
  const labels = [];
147
150
  for (const { clip, buffer } of usable) {
148
151
  signal?.throwIfAborted();
149
- const p = join3(workDir, `clip-${inputs.length}.mp3`);
150
- await writeFile2(p, new Uint8Array(buffer));
152
+ const p = join5(workDir, `clip-${inputs.length}.mp3`);
153
+ await writeFile3(p, new Uint8Array(buffer));
151
154
  signal?.throwIfAborted();
152
155
  const i = inputs.push(p) - 1;
153
156
  filters.push(`[${i}:a]${clipFilterChain(clip)}[a${i}]`);
154
157
  labels.push(`[a${i}]`);
155
158
  }
156
159
  const graph = `${filters.join(";")};${labels.join("")}amix=inputs=${labels.length}:normalize=0:dropout_transition=0[aout]`;
157
- const outputPath = join3(workDir, "mixed.mp3");
160
+ const outputPath = join5(workDir, "mixed.mp3");
158
161
  const args = ["-y"];
159
162
  for (const p of inputs) args.push("-i", p);
160
163
  args.push(
@@ -174,11 +177,11 @@ async function mixTimelineClips(ffmpegPath, usable, signal) {
174
177
  signal
175
178
  });
176
179
  signal?.throwIfAborted();
177
- const data = await readFile4(outputPath);
180
+ const data = await readFile5(outputPath);
178
181
  signal?.throwIfAborted();
179
182
  return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
180
183
  } finally {
181
- await rm2(workDir, { recursive: true, force: true });
184
+ await rm3(workDir, { recursive: true, force: true });
182
185
  }
183
186
  }
184
187
 
@@ -321,11 +324,188 @@ function isRecord(value) {
321
324
  return typeof value === "object" && value !== null;
322
325
  }
323
326
 
327
+ // src/util/frameSink.ts
328
+ import { spawn } from "child_process";
329
+ import { createHash } from "crypto";
330
+ import { once } from "events";
331
+ import { access, mkdir, readFile, writeFile } from "fs/promises";
332
+ import { join } from "path";
333
+ import { isDeepStrictEqual } from "util";
334
+ import {
335
+ audioBitrateArg,
336
+ ffmpegAudioMuxArgs,
337
+ ffmpegVideoQualityArgs
338
+ } from "@bendyline/squisq-video";
339
+ function ffmpegPipeArgs(options) {
340
+ const { outputPath, fps, width, height, quality, captureFormat, audioPath } = options;
341
+ const args = [
342
+ "-y",
343
+ "-f",
344
+ "image2pipe",
345
+ "-framerate",
346
+ String(fps),
347
+ "-c:v",
348
+ captureFormat === "jpeg" ? "mjpeg" : "png",
349
+ "-i",
350
+ "pipe:0"
351
+ ];
352
+ if (audioPath) args.push("-i", audioPath);
353
+ const range = captureFormat === "jpeg" ? ":in_range=pc:out_range=tv" : "";
354
+ args.push(
355
+ "-c:v",
356
+ "libx264",
357
+ ...ffmpegVideoQualityArgs(quality),
358
+ "-pix_fmt",
359
+ "yuv420p",
360
+ "-color_range",
361
+ "tv",
362
+ "-vf",
363
+ `scale=${width}:${height}:force_original_aspect_ratio=decrease${range},pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2`
364
+ );
365
+ if (audioPath) args.push(...ffmpegAudioMuxArgs(audioBitrateArg(quality)));
366
+ args.push("-movflags", "+faststart", outputPath);
367
+ return args;
368
+ }
369
+ var STDERR_TAIL_LINES = 200;
370
+ var IDLE_POLL_MS = 5e3;
371
+ function createFfmpegPipeSink(options) {
372
+ const { ffmpegPath, signal, idleTimeoutMs = 12e4 } = options;
373
+ const child = spawn(ffmpegPath, ffmpegPipeArgs(options), {
374
+ stdio: ["pipe", "ignore", "pipe"]
375
+ });
376
+ const stderrTail = [];
377
+ let lastActivity = Date.now();
378
+ let failure = null;
379
+ let frames = 0;
380
+ let exitCode;
381
+ child.stderr.setEncoding("utf8");
382
+ child.stderr.on("data", (chunk) => {
383
+ lastActivity = Date.now();
384
+ for (const line of chunk.split(/\r?\n|\r/)) {
385
+ if (!line.trim()) continue;
386
+ stderrTail.push(line);
387
+ if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
388
+ }
389
+ });
390
+ child.on("error", (err) => {
391
+ failure ??= err;
392
+ });
393
+ child.stdin.on("error", (err) => {
394
+ failure ??= err;
395
+ });
396
+ const exited = new Promise((resolve2) => {
397
+ child.on("exit", (code) => {
398
+ exitCode = code;
399
+ resolve2();
400
+ });
401
+ child.on("error", () => resolve2());
402
+ });
403
+ const idleTimer = setInterval(() => {
404
+ if (Date.now() - lastActivity > idleTimeoutMs) {
405
+ failure ??= new Error(`ffmpeg produced no output for ${Math.round(idleTimeoutMs / 1e3)}s`);
406
+ child.kill("SIGKILL");
407
+ }
408
+ }, IDLE_POLL_MS);
409
+ idleTimer.unref();
410
+ const onAbort = () => {
411
+ child.kill("SIGKILL");
412
+ };
413
+ signal?.addEventListener("abort", onAbort, { once: true });
414
+ const cleanup = () => {
415
+ clearInterval(idleTimer);
416
+ signal?.removeEventListener("abort", onAbort);
417
+ };
418
+ const describeFailure = () => {
419
+ const detail = lastMeaningfulFfmpegLine(stderrTail.join("\n"));
420
+ if (failure && failure.code === "ENOENT") {
421
+ return "the ffmpeg binary could not be started (ENOENT). Run `squisq doctor` to check your FFmpeg installation.";
422
+ }
423
+ const head = failure ? failure.message : exitCode === void 0 ? "ffmpeg exited unexpectedly" : `ffmpeg exited unsuccessfully (exit code ${exitCode})`;
424
+ return detail ? `${head} (last output: ${detail})` : head;
425
+ };
426
+ const throwIfDead = () => {
427
+ signal?.throwIfAborted();
428
+ if (failure || exitCode !== void 0) {
429
+ throw new Error(`ffmpeg failed: ${describeFailure()}`);
430
+ }
431
+ };
432
+ return {
433
+ get frameCount() {
434
+ return frames;
435
+ },
436
+ async write(frame, repeat = 1) {
437
+ if (!Number.isSafeInteger(repeat) || repeat < 1) {
438
+ throw new Error("Frame repetition count must be a positive integer");
439
+ }
440
+ throwIfDead();
441
+ for (let i = 0; i < repeat; i += 1) {
442
+ lastActivity = Date.now();
443
+ if (!child.stdin.write(frame)) {
444
+ await Promise.race([once(child.stdin, "drain").catch(() => void 0), exited]);
445
+ }
446
+ throwIfDead();
447
+ frames += 1;
448
+ }
449
+ },
450
+ async finish() {
451
+ throwIfDead();
452
+ child.stdin.end();
453
+ await exited;
454
+ cleanup();
455
+ signal?.throwIfAborted();
456
+ if (failure || exitCode !== 0) throw new Error(`ffmpeg failed: ${describeFailure()}`);
457
+ },
458
+ async abort() {
459
+ cleanup();
460
+ if (exitCode === void 0) child.kill("SIGKILL");
461
+ await exited;
462
+ }
463
+ };
464
+ }
465
+ function docRenderHash(doc) {
466
+ return createHash("sha256").update(JSON.stringify(doc)).digest("hex");
467
+ }
468
+ var MANIFEST_NAME = "manifest.json";
469
+ async function openDirectoryFrameStore(dir, manifest, resume) {
470
+ await mkdir(dir, { recursive: true });
471
+ const manifestPath = join(dir, MANIFEST_NAME);
472
+ let existing = null;
473
+ try {
474
+ existing = JSON.parse(await readFile(manifestPath, "utf8"));
475
+ } catch {
476
+ existing = null;
477
+ }
478
+ const reusable = resume && existing !== null && isDeepStrictEqual(existing, manifest);
479
+ if (!reusable) await writeFile(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
480
+ const extension = manifest.captureFormat === "jpeg" ? "jpg" : "png";
481
+ const path = (index) => join(dir, `frame-${String(index).padStart(6, "0")}.${extension}`);
482
+ return {
483
+ dir,
484
+ reusable,
485
+ path,
486
+ async has(index) {
487
+ try {
488
+ await access(path(index));
489
+ return true;
490
+ } catch {
491
+ return false;
492
+ }
493
+ },
494
+ async read(index) {
495
+ const bytes = await readFile(path(index));
496
+ return new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
497
+ },
498
+ async write(index, frame) {
499
+ await writeFile(path(index), frame);
500
+ }
501
+ };
502
+ }
503
+
324
504
  // src/registry.ts
325
505
  import { randomBytes } from "crypto";
326
- import { readFile, rm } from "fs/promises";
506
+ import { readFile as readFile2, rm } from "fs/promises";
327
507
  import { tmpdir } from "os";
328
- import { join } from "path";
508
+ import { join as join2 } from "path";
329
509
  import { defaultRegistry } from "@bendyline/squisq-formats";
330
510
  var MP4_DEFAULTS = {
331
511
  fps: 30,
@@ -360,9 +540,9 @@ function mp4Format() {
360
540
  const orientation = typeof mp4Opts.orientation === "string" ? mp4Opts.orientation : MP4_DEFAULTS.orientation;
361
541
  const coverPreRoll = typeof mp4Opts.coverPreRoll === "number" ? mp4Opts.coverPreRoll : MP4_DEFAULTS.coverPreRoll;
362
542
  const animationsEnabled = typeof mp4Opts.animationsEnabled === "boolean" ? mp4Opts.animationsEnabled : MP4_DEFAULTS.animationsEnabled;
363
- const outputPath = join(tmpdir(), `squisq-mp4-${randomBytes(8).toString("hex")}.mp4`);
543
+ const outputPath = join2(tmpdir(), `squisq-mp4-${randomBytes(8).toString("hex")}.mp4`);
364
544
  try {
365
- const { renderDocToMp4: renderDocToMp42 } = await import("./api-QLYK5AQE.js");
545
+ const { renderDocToMp4: renderDocToMp42 } = await import("./api-O34CQ6ZP.js");
366
546
  await renderDocToMp42(input.doc, input.container, {
367
547
  outputPath,
368
548
  fps,
@@ -377,7 +557,7 @@ function mp4Format() {
377
557
  onProgress: mp4Opts.onProgress
378
558
  });
379
559
  options.signal?.throwIfAborted();
380
- const data = await readFile(outputPath, { signal: options.signal });
560
+ const data = await readFile2(outputPath, { signal: options.signal });
381
561
  options.signal?.throwIfAborted();
382
562
  const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
383
563
  return { bytes, mimeType: "video/mp4", suggestedFilename: "", warnings: [] };
@@ -401,9 +581,9 @@ function gifFormat() {
401
581
  const portrait = orientation === "portrait";
402
582
  const defaultWidth = portrait ? GIF_DEFAULTS.height : GIF_DEFAULTS.width;
403
583
  const defaultHeight = portrait ? GIF_DEFAULTS.width : GIF_DEFAULTS.height;
404
- const outputPath = join(tmpdir(), `squisq-gif-${randomBytes(8).toString("hex")}.gif`);
584
+ const outputPath = join2(tmpdir(), `squisq-gif-${randomBytes(8).toString("hex")}.gif`);
405
585
  try {
406
- const { renderDocToGif: renderDocToGif2 } = await import("./api-QLYK5AQE.js");
586
+ const { renderDocToGif: renderDocToGif2 } = await import("./api-O34CQ6ZP.js");
407
587
  const result = await renderDocToGif2(input.doc, input.container, {
408
588
  outputPath,
409
589
  fps: typeof gifOpts.fps === "number" ? gifOpts.fps : GIF_DEFAULTS.fps,
@@ -421,7 +601,7 @@ function gifFormat() {
421
601
  onProgress: gifOpts.onProgress
422
602
  });
423
603
  options.signal?.throwIfAborted();
424
- const data = await readFile(outputPath, { signal: options.signal });
604
+ const data = await readFile2(outputPath, { signal: options.signal });
425
605
  options.signal?.throwIfAborted();
426
606
  const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
427
607
  return {
@@ -446,7 +626,7 @@ function pngFormat() {
446
626
  async exportDoc(input, options) {
447
627
  options.signal?.throwIfAborted();
448
628
  const pngOpts = options.formatOptions?.png ?? {};
449
- const { renderDocToDashboardPng: renderDocToDashboardPng2 } = await import("./api-QLYK5AQE.js");
629
+ const { renderDocToDashboardPng: renderDocToDashboardPng2 } = await import("./api-O34CQ6ZP.js");
450
630
  const result = await renderDocToDashboardPng2(input.doc, input.container, {
451
631
  resolution: pngOpts.resolution,
452
632
  width: pngOpts.width,
@@ -475,13 +655,13 @@ function createCliRegistry() {
475
655
  import { MemoryContentContainer as MemoryContentContainer2 } from "@bendyline/squisq/storage";
476
656
 
477
657
  // src/util/readInput.ts
478
- import { readFile as readFile2, readdir, realpath, stat } from "fs/promises";
658
+ import { readFile as readFile3, readdir, realpath, stat } from "fs/promises";
479
659
  import {
480
660
  basename,
481
661
  dirname,
482
662
  extname,
483
663
  isAbsolute,
484
- join as join2,
664
+ join as join3,
485
665
  posix,
486
666
  relative,
487
667
  resolve,
@@ -547,7 +727,7 @@ async function walkDir(root, prefix = "", signal) {
547
727
  throwIfAborted(signal);
548
728
  const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
549
729
  if (entry.isDirectory()) {
550
- paths.push(...await walkDir(join2(root, entry.name), relPath, signal));
730
+ paths.push(...await walkDir(join3(root, entry.name), relPath, signal));
551
731
  } else if (entry.isFile()) {
552
732
  paths.push(relPath);
553
733
  }
@@ -598,7 +778,7 @@ async function readArrayBuffer(filePath, signal) {
598
778
  async function readBinaryFile(filePath, signal) {
599
779
  throwIfAborted(signal);
600
780
  try {
601
- const data = await readFile2(filePath, { signal });
781
+ const data = await readFile3(filePath, { signal });
602
782
  throwIfAborted(signal);
603
783
  return data;
604
784
  } catch (error) {
@@ -609,7 +789,7 @@ async function readBinaryFile(filePath, signal) {
609
789
  async function readUtf8File(filePath, signal) {
610
790
  throwIfAborted(signal);
611
791
  try {
612
- const content = await readFile2(filePath, { encoding: "utf-8", signal });
792
+ const content = await readFile3(filePath, { encoding: "utf-8", signal });
613
793
  throwIfAborted(signal);
614
794
  return content;
615
795
  } catch (error) {
@@ -864,7 +1044,7 @@ async function readFolder(dirPath, signal) {
864
1044
  throwIfAborted(signal);
865
1045
  for (const relPath of files) {
866
1046
  throwIfAborted(signal);
867
- const absPath = join2(dirPath, relPath);
1047
+ const absPath = join3(dirPath, relPath);
868
1048
  const data = await readBinaryFile(absPath, signal);
869
1049
  throwIfAborted(signal);
870
1050
  await container.writeFile(
@@ -898,11 +1078,13 @@ import {
898
1078
  validateDashboardImageDimensions
899
1079
  } from "@bendyline/squisq-video";
900
1080
  import { ConversionError } from "@bendyline/squisq-formats";
1081
+ var RENDER_BOOT_TIMEOUT_MS = 6e4;
1082
+ var JPEG_CAPTURE_QUALITY = 92;
901
1083
  var playerBundlePromise;
902
1084
  var fullPlayerBundlePromise;
903
1085
  var playerIconBootstrapPromise;
904
1086
  function loadPlayerIconBootstrap() {
905
- playerIconBootstrapPromise ??= readFile3(
1087
+ playerIconBootstrapPromise ??= readFile4(
906
1088
  new URL("../dist/squisq-player-icons.global.js", import.meta.url),
907
1089
  "utf8"
908
1090
  );
@@ -911,14 +1093,14 @@ function loadPlayerIconBootstrap() {
911
1093
  function loadPlayerBundle() {
912
1094
  playerBundlePromise ??= Promise.all([
913
1095
  loadPlayerIconBootstrap(),
914
- readFile3(new URL("../dist/squisq-player.global.js", import.meta.url), "utf8")
1096
+ readFile4(new URL("../dist/squisq-player.global.js", import.meta.url), "utf8")
915
1097
  ]).then(([icons, player]) => `${icons}${player}`);
916
1098
  return playerBundlePromise;
917
1099
  }
918
1100
  function loadFullPlayerBundle() {
919
1101
  fullPlayerBundlePromise ??= Promise.all([
920
1102
  loadPlayerIconBootstrap(),
921
- readFile3(new URL("../dist/squisq-player.full.global.js", import.meta.url), "utf8")
1103
+ readFile4(new URL("../dist/squisq-player.full.global.js", import.meta.url), "utf8")
922
1104
  ]).then(([icons, player]) => `${icons}${player}`);
923
1105
  return fullPlayerBundlePromise;
924
1106
  }
@@ -1052,7 +1234,7 @@ async function withRenderPage(doc, container, options, fn) {
1052
1234
  const player = window.SquisqPlayer;
1053
1235
  return root ? player?.getHandle(root)?.getRenderAPI() != null : false;
1054
1236
  },
1055
- { timeout: 15e3 }
1237
+ { timeout: RENDER_BOOT_TIMEOUT_MS }
1056
1238
  );
1057
1239
  } catch {
1058
1240
  signal?.throwIfAborted();
@@ -1060,7 +1242,7 @@ async function withRenderPage(doc, container, options, fn) {
1060
1242
  Page errors:
1061
1243
  ${pageErrors.join("\n ")}` : "\nNo page errors captured \u2014 the player may have failed to mount.";
1062
1244
  throw new Error(
1063
- `The standalone player failed to boot in headless Chromium. Render API did not initialize within 15 seconds.${errorDetail}`
1245
+ `The standalone player failed to boot in headless Chromium. Render API did not initialize within ${RENDER_BOOT_TIMEOUT_MS / 1e3} seconds.${errorDetail}`
1064
1246
  );
1065
1247
  }
1066
1248
  renderAPI = await page.evaluateHandle(() => {
@@ -1071,6 +1253,13 @@ Page errors:
1071
1253
  return api;
1072
1254
  });
1073
1255
  signal?.throwIfAborted();
1256
+ const mounted = await renderAPI.evaluate((api) => api.getViewport ? api.getViewport() : null);
1257
+ signal?.throwIfAborted();
1258
+ if (mounted && (mounted.width !== width || mounted.height !== height)) {
1259
+ throw new Error(
1260
+ `The player composed a ${mounted.width}x${mounted.height} viewport for a ${width}x${height} render; the output would be letterboxed. Rebuild the CLI player bundle (npm run build:cli) so the render page can pin its viewport.`
1261
+ );
1262
+ }
1074
1263
  return await fn({ page, renderAPI });
1075
1264
  } finally {
1076
1265
  signal?.removeEventListener("abort", handleAbort);
@@ -1078,10 +1267,7 @@ Page errors:
1078
1267
  await browser.close().catch(() => void 0);
1079
1268
  }
1080
1269
  }
1081
- async function captureDocFrames(doc, container, options) {
1082
- const { fps, width, height, captionStyle, coverPreRoll, animationsEnabled, onProgress, signal } = options;
1083
- signal?.throwIfAborted();
1084
- resolveAppliedCoverPreRoll(coverPreRoll, true);
1270
+ async function requireFfmpeg(signal) {
1085
1271
  const ffmpegPath = (await detectFfmpegDetailed(signal))?.path ?? null;
1086
1272
  signal?.throwIfAborted();
1087
1273
  if (!ffmpegPath) {
@@ -1089,53 +1275,87 @@ async function captureDocFrames(doc, container, options) {
1089
1275
  "ffmpeg is required but not found in PATH.\nInstall it with:\n macOS: brew install ffmpeg\n Ubuntu: sudo apt install ffmpeg\n Windows: winget install ffmpeg\nOr: npm install ffmpeg-static, or set SQUISQ_FFMPEG to an ffmpeg binary."
1090
1276
  );
1091
1277
  }
1278
+ return ffmpegPath;
1279
+ }
1280
+ async function iterateDocFrames(session, options, visit) {
1281
+ const { page, renderAPI } = session;
1282
+ const { fps, coverPreRoll, captureFormat, signal, onProgress } = options;
1283
+ const screenshot = () => captureFormat === "jpeg" ? page.screenshot({ type: "jpeg", quality: JPEG_CAPTURE_QUALITY }) : page.screenshot({ type: "png" });
1284
+ const docDuration = await renderAPI.evaluate((api) => api.getDuration());
1285
+ signal?.throwIfAborted();
1286
+ if (docDuration <= 0) throw new Error("Document has zero duration \u2014 nothing to render");
1287
+ const hasCover = coverPreRoll > 0 ? await renderAPI.evaluate((api) => api.hasCoverBlock()) : false;
1288
+ const appliedCoverPreRoll = resolveAppliedCoverPreRoll(coverPreRoll, hasCover);
1289
+ const storyFrameCount = Math.ceil(docDuration * fps);
1290
+ const preRollFrameCount = Math.ceil(appliedCoverPreRoll * fps);
1291
+ const totalFrames = preRollFrameCount + storyFrameCount;
1292
+ onProgress?.("capturing frames", 20);
1293
+ if (preRollFrameCount > 0) {
1294
+ signal?.throwIfAborted();
1295
+ await visit(
1296
+ { index: 0, time: 0, isCover: true, repeat: preRollFrameCount, totalFrames },
1297
+ async () => {
1298
+ await renderAPI.evaluate((api) => api.showCover());
1299
+ await page.waitForTimeout(100);
1300
+ signal?.throwIfAborted();
1301
+ const frame = await screenshot();
1302
+ await renderAPI.evaluate((api) => api.hideCover());
1303
+ return frame;
1304
+ }
1305
+ );
1306
+ }
1307
+ const progressEvery = Math.max(1, Math.floor(fps / 2));
1308
+ for (let i = 0; i < storyFrameCount; i++) {
1309
+ signal?.throwIfAborted();
1310
+ const time = frameTimeSeconds(i, fps);
1311
+ await visit(
1312
+ { index: preRollFrameCount + i, time, isCover: false, repeat: 1, totalFrames },
1313
+ async () => {
1314
+ await renderAPI.evaluate((api, t) => api.seekTo(t), time);
1315
+ signal?.throwIfAborted();
1316
+ return screenshot();
1317
+ }
1318
+ );
1319
+ if (i % progressEvery === 0 || i === storyFrameCount - 1) {
1320
+ onProgress?.(
1321
+ "capturing frames",
1322
+ 20 + Math.round((preRollFrameCount + i + 1) / totalFrames * 60)
1323
+ );
1324
+ }
1325
+ }
1326
+ return {
1327
+ totalDuration: docDuration + appliedCoverPreRoll,
1328
+ appliedCoverPreRoll,
1329
+ totalFrames,
1330
+ preRollFrameCount
1331
+ };
1332
+ }
1333
+ async function captureDocFrames(doc, container, options) {
1334
+ const { fps, width, height, captionStyle, coverPreRoll, animationsEnabled, onProgress, signal } = options;
1335
+ signal?.throwIfAborted();
1336
+ resolveAppliedCoverPreRoll(coverPreRoll, true);
1337
+ const ffmpegPath = await requireFfmpeg(signal);
1092
1338
  const capturedFrames = new CapturedFrameCollector();
1093
1339
  try {
1094
1340
  return await withRenderPage(
1095
1341
  doc,
1096
1342
  container,
1097
1343
  { signal, width, height, includeAudio: true, captionStyle, animationsEnabled, onProgress },
1098
- async ({ page, renderAPI }) => {
1099
- const docDuration = await renderAPI.evaluate((api) => api.getDuration());
1100
- signal?.throwIfAborted();
1101
- if (docDuration <= 0) throw new Error("Document has zero duration \u2014 nothing to render");
1102
- const hasCover = coverPreRoll > 0 ? await renderAPI.evaluate((api) => api.hasCoverBlock()) : false;
1103
- const appliedCoverPreRoll = resolveAppliedCoverPreRoll(coverPreRoll, hasCover);
1104
- const storyFrameCount = Math.ceil(docDuration * fps);
1105
- const preRollFrameCount = Math.ceil(appliedCoverPreRoll * fps);
1106
- const totalFrames = preRollFrameCount + storyFrameCount;
1107
- onProgress?.("capturing frames", 20);
1108
- capturedFrames.throwIfAborted(signal);
1109
- if (preRollFrameCount > 0) {
1110
- capturedFrames.throwIfAborted(signal);
1111
- await renderAPI.evaluate((api) => api.showCover());
1112
- await page.waitForTimeout(100);
1113
- capturedFrames.throwIfAborted(signal);
1114
- const coverFrame = await page.screenshot({ type: "png" });
1115
- capturedFrames.throwIfAborted(signal);
1116
- capturedFrames.append(coverFrame, preRollFrameCount);
1117
- await renderAPI.evaluate((api) => api.hideCover());
1118
- }
1119
- const frameInterval = 1 / fps;
1120
- for (let i = 0; i < storyFrameCount; i++) {
1121
- capturedFrames.throwIfAborted(signal);
1122
- const time = i * frameInterval;
1123
- await renderAPI.evaluate((api, t) => api.seekTo(t), time);
1124
- const frame = await page.screenshot({ type: "png" });
1125
- capturedFrames.throwIfAborted(signal);
1126
- capturedFrames.append(frame);
1127
- if (i % Math.max(1, Math.floor(fps / 2)) === 0 || i === storyFrameCount - 1) {
1128
- onProgress?.(
1129
- "capturing frames",
1130
- 20 + Math.round(capturedFrames.frameCount / totalFrames * 60)
1131
- );
1344
+ async (session) => {
1345
+ const loop = await iterateDocFrames(
1346
+ session,
1347
+ { fps, coverPreRoll, captureFormat: "png", signal, onProgress },
1348
+ async (frame, capture) => {
1132
1349
  capturedFrames.throwIfAborted(signal);
1350
+ const bytes = await capture();
1351
+ capturedFrames.throwIfAborted(signal);
1352
+ capturedFrames.append(bytes, frame.repeat);
1133
1353
  }
1134
- }
1354
+ );
1135
1355
  return {
1136
1356
  frames: capturedFrames.release(),
1137
- totalDuration: docDuration + appliedCoverPreRoll,
1138
- appliedCoverPreRoll,
1357
+ totalDuration: loop.totalDuration,
1358
+ appliedCoverPreRoll: loop.appliedCoverPreRoll,
1139
1359
  ffmpegPath
1140
1360
  };
1141
1361
  }
@@ -1146,6 +1366,119 @@ async function captureDocFrames(doc, container, options) {
1146
1366
  throw err;
1147
1367
  }
1148
1368
  }
1369
+ async function renderDocToMp4Piped(doc, container, options, render) {
1370
+ const { signal, onProgress } = options;
1371
+ const { fps, quality, width, height, captureFormat } = render;
1372
+ const coverPreRoll = options.coverPreRoll ?? 0;
1373
+ resolveAppliedCoverPreRoll(coverPreRoll, true);
1374
+ if (options.resume && !options.framesDir) {
1375
+ throw new Error("resume requires framesDir so there is a spool to resume from");
1376
+ }
1377
+ const captionStyle = options.captionStyle === "off" ? void 0 : options.captionStyle;
1378
+ const animationsEnabled = options.animationsEnabled ?? true;
1379
+ const ffmpegPath = await requireFfmpeg(signal);
1380
+ const outputPath = resolvePath(options.outputPath);
1381
+ await mkdir2(dirname2(outputPath), { recursive: true });
1382
+ const manifest = {
1383
+ generatedBy: "squisq-cli",
1384
+ docHash: docRenderHash(doc),
1385
+ fps,
1386
+ width,
1387
+ height,
1388
+ captionStyle: captionStyle ?? null,
1389
+ animationsEnabled,
1390
+ coverPreRoll,
1391
+ captureFormat
1392
+ };
1393
+ const store = options.framesDir ? await openDirectoryFrameStore(
1394
+ resolvePath(options.framesDir),
1395
+ manifest,
1396
+ options.resume === true
1397
+ ) : null;
1398
+ const audioPath = join4(tmpdir2(), `squisq-audio-${randomBytes2(8).toString("hex")}.mp3`);
1399
+ let audioWritten = false;
1400
+ let sink = null;
1401
+ let reusedFrameCount = 0;
1402
+ try {
1403
+ const { loop, activeSink } = await withRenderPage(
1404
+ doc,
1405
+ container,
1406
+ { signal, width, height, includeAudio: true, captionStyle, animationsEnabled, onProgress },
1407
+ async (session) => {
1408
+ const hasCover = coverPreRoll > 0 ? await session.renderAPI.evaluate((api) => api.hasCoverBlock()) : false;
1409
+ const appliedCoverPreRoll = resolveAppliedCoverPreRoll(coverPreRoll, hasCover);
1410
+ onProgress?.("mixing audio", 18);
1411
+ const encodingAudio = await buildMixedAudioTrack(
1412
+ doc,
1413
+ container,
1414
+ ffmpegPath,
1415
+ appliedCoverPreRoll,
1416
+ signal
1417
+ );
1418
+ signal?.throwIfAborted();
1419
+ if (encodingAudio) {
1420
+ await writeFile2(audioPath, encodingAudio);
1421
+ audioWritten = true;
1422
+ }
1423
+ const pipe = createFfmpegPipeSink({
1424
+ ffmpegPath,
1425
+ outputPath,
1426
+ fps,
1427
+ width,
1428
+ height,
1429
+ quality,
1430
+ captureFormat,
1431
+ audioPath: audioWritten ? audioPath : null,
1432
+ signal
1433
+ });
1434
+ sink = pipe;
1435
+ const result = await iterateDocFrames(
1436
+ session,
1437
+ { fps, coverPreRoll, captureFormat, signal, onProgress },
1438
+ async (frame, capture) => {
1439
+ const started = Date.now();
1440
+ let bytes;
1441
+ let reused = false;
1442
+ if (store?.reusable && await store.has(frame.index)) {
1443
+ bytes = await store.read(frame.index);
1444
+ reused = true;
1445
+ reusedFrameCount += frame.repeat;
1446
+ } else {
1447
+ bytes = await capture();
1448
+ if (store) await store.write(frame.index, bytes);
1449
+ }
1450
+ await pipe.write(bytes, frame.repeat);
1451
+ options.onFrame?.({
1452
+ index: frame.index,
1453
+ time: frame.time,
1454
+ isCover: frame.isCover,
1455
+ totalFrames: frame.totalFrames,
1456
+ reused,
1457
+ captureMs: reused ? 0 : Date.now() - started
1458
+ });
1459
+ }
1460
+ );
1461
+ return { loop: result, activeSink: pipe };
1462
+ }
1463
+ );
1464
+ onProgress?.("encoding video", 85);
1465
+ await activeSink.finish();
1466
+ signal?.throwIfAborted();
1467
+ onProgress?.("done", 100);
1468
+ return {
1469
+ duration: loop.totalDuration,
1470
+ frameCount: activeSink.frameCount,
1471
+ outputPath,
1472
+ reusedFrameCount,
1473
+ ...store ? { framesDir: store.dir } : {}
1474
+ };
1475
+ } catch (err) {
1476
+ await sink?.abort();
1477
+ throw err;
1478
+ } finally {
1479
+ if (audioWritten) await rm2(audioPath, { force: true }).catch(() => void 0);
1480
+ }
1481
+ }
1149
1482
  async function renderDocCoverToPng(doc, container, options = {}) {
1150
1483
  const width = options.width ?? 1920;
1151
1484
  const height = options.height ?? 1080;
@@ -1178,8 +1511,8 @@ async function renderDocCoverToPng(doc, container, options = {}) {
1178
1511
  let writtenPath;
1179
1512
  if (options.outputPath) {
1180
1513
  const absolute = resolvePath(options.outputPath);
1181
- await mkdir(dirname2(absolute), { recursive: true });
1182
- await writeFile(absolute, bytes);
1514
+ await mkdir2(dirname2(absolute), { recursive: true });
1515
+ await writeFile2(absolute, bytes);
1183
1516
  writtenPath = absolute;
1184
1517
  }
1185
1518
  options.onProgress?.("done", 100);
@@ -1227,8 +1560,8 @@ async function renderDocToDashboardPng(doc, container, options = {}) {
1227
1560
  let writtenPath;
1228
1561
  if (outputPath) {
1229
1562
  const absolute = resolvePath(outputPath);
1230
- await mkdir(dirname2(absolute), { recursive: true });
1231
- await writeFile(absolute, bytes);
1563
+ await mkdir2(dirname2(absolute), { recursive: true });
1564
+ await writeFile2(absolute, bytes);
1232
1565
  writtenPath = absolute;
1233
1566
  }
1234
1567
  onProgress?.("done", 100);
@@ -1251,6 +1584,20 @@ async function renderDocToMp4(doc, container, options) {
1251
1584
  fps,
1252
1585
  quality
1253
1586
  });
1587
+ const frameTransport = options.frameTransport ?? "pipe";
1588
+ const captureFormat = options.captureFormat ?? (quality === "high" ? "png" : "jpeg");
1589
+ if (frameTransport === "pipe") {
1590
+ return renderDocToMp4Piped(doc, container, options, {
1591
+ fps,
1592
+ quality,
1593
+ width: dimensions.width,
1594
+ height: dimensions.height,
1595
+ captureFormat
1596
+ });
1597
+ }
1598
+ if (options.framesDir || options.resume || options.onFrame) {
1599
+ throw new Error("framesDir, resume, and onFrame require the pipe frame transport");
1600
+ }
1254
1601
  const capture = await captureDocFrames(doc, container, {
1255
1602
  fps,
1256
1603
  width: dimensions.width,
@@ -1273,7 +1620,7 @@ async function renderDocToMp4(doc, container, options) {
1273
1620
  options.signal
1274
1621
  );
1275
1622
  options.signal?.throwIfAborted();
1276
- const { framesToMp4Native: framesToMp4Native2 } = await import("./nativeEncoder-PMVSFLMN.js");
1623
+ const { framesToMp4Native: framesToMp4Native2 } = await import("./nativeEncoder-RILHXTXI.js");
1277
1624
  await framesToMp4Native2(capture.ffmpegPath, capture.frames, encodingAudio, options.outputPath, {
1278
1625
  fps,
1279
1626
  quality,
@@ -1328,7 +1675,7 @@ async function renderDocToGif(doc, container, options) {
1328
1675
  try {
1329
1676
  options.onProgress?.("encoding GIF", 80);
1330
1677
  options.signal?.throwIfAborted();
1331
- const { framesToGifNative: framesToGifNative2 } = await import("./nativeEncoder-PMVSFLMN.js");
1678
+ const { framesToGifNative: framesToGifNative2 } = await import("./nativeEncoder-RILHXTXI.js");
1332
1679
  await framesToGifNative2(capture.ffmpegPath, capture.frames, options.outputPath, {
1333
1680
  fps,
1334
1681
  orientation,
@@ -1358,7 +1705,7 @@ async function renderDocToGif(doc, container, options) {
1358
1705
  async function extractThumbnails(options) {
1359
1706
  const { videoPath, outputDir, slug, sizes, force, signal } = options;
1360
1707
  const { existsSync } = await import("fs");
1361
- const { rm: rm2 } = await import("fs/promises");
1708
+ const { rm: rm3 } = await import("fs/promises");
1362
1709
  const { isAbsolute: isAbsolute2, relative: relative2, resolve: resolve2, sep: sep2 } = await import("path");
1363
1710
  signal?.throwIfAborted();
1364
1711
  if (typeof slug !== "string" || !/^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,126}[A-Za-z0-9])?$/.test(slug)) {
@@ -1408,13 +1755,13 @@ async function extractThumbnails(options) {
1408
1755
  signal?.throwIfAborted();
1409
1756
  generatedPaths.push(outputPath);
1410
1757
  } catch (error) {
1411
- await rm2(outputPath, { force: true });
1758
+ await rm3(outputPath, { force: true });
1412
1759
  throw error;
1413
1760
  }
1414
1761
  }
1415
1762
  signal?.throwIfAborted();
1416
1763
  } catch (error) {
1417
- await Promise.allSettled(generatedPaths.map((path) => rm2(path, { force: true })));
1764
+ await Promise.allSettled(generatedPaths.map((path) => rm3(path, { force: true })));
1418
1765
  throw error;
1419
1766
  }
1420
1767
  }
@@ -1426,6 +1773,7 @@ export {
1426
1773
  detectFfmpegDetailed,
1427
1774
  MAX_CAPTURED_FRAME_BYTES,
1428
1775
  CapturedFrameBudgetError,
1776
+ ffmpegPipeArgs,
1429
1777
  convert,
1430
1778
  prepareConversion,
1431
1779
  renderDocCoverToPng,