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