@holtjs/stage 0.13.0 → 0.15.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/headless.js CHANGED
@@ -1,8 +1,127 @@
1
1
  import "./types-CXsCvp1p.js";
2
- import { n as Game } from "./game-CziLa7dv.js";
3
- import { a as requestHeadlessWebGpu, i as openWgpuNativeFfi, r as openDawnWebGpu } from "./renderer-webgpu-LDnrpYa0.js";
2
+ import { n as Game } from "./game-CFxS641c.js";
3
+ import { a as requestHeadlessWebGpu, i as openWgpuNativeFfi, r as openDawnWebGpu } from "./renderer-webgpu-q4vdE3kA.js";
4
4
  import { buildSceneDigest } from "./trace.js";
5
5
  // src/headless.ts
6
+ let pngCrcTable = null;
7
+ function getPngCrcTable() {
8
+ if (pngCrcTable) return pngCrcTable;
9
+ const table = /* @__PURE__ */ new Uint32Array(256);
10
+ for (let n = 0; n < 256; n++) {
11
+ let c = n;
12
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ c >>> 1 : c >>> 1;
13
+ table[n] = c >>> 0;
14
+ }
15
+ pngCrcTable = table;
16
+ return table;
17
+ }
18
+ function pngCrc32(buf, start, len) {
19
+ const table = getPngCrcTable();
20
+ let c = 0xffffffff;
21
+ for (let i = 0; i < len; i++) c = table[(c ^ buf[start + i]) & 255] ^ c >>> 8;
22
+ return (c ^ 0xffffffff) >>> 0;
23
+ }
24
+ /** Zero-dependency pure-TS RGBA8888 -> PNG encoder (used when running pure WebGPU/WebGL without `@napi-rs/canvas`). */
25
+ function encodeRgbaToPngFallback(rgba, width, height) {
26
+ const rowStride = width * 4;
27
+ const rawLen = height * (1 + rowStride);
28
+ const raw = new Uint8Array(rawLen);
29
+ let s1 = 1;
30
+ let s2 = 0;
31
+ let dstOff = 0;
32
+ for (let y = 0; y < height; y++) {
33
+ raw[dstOff++] = 0;
34
+ s2 = (s2 + s1) % 65521;
35
+ const srcRow = y * rowStride;
36
+ for (let x = 0; x < rowStride; x++) {
37
+ const b = rgba[srcRow + x];
38
+ raw[dstOff++] = b;
39
+ s1 = (s1 + b) % 65521;
40
+ s2 = (s2 + s1) % 65521;
41
+ }
42
+ }
43
+ const adler = (s2 << 16 | s1) >>> 0;
44
+ const numBlocks = Math.max(1, Math.ceil(rawLen / 65535));
45
+ const idatDataLen = 2 + rawLen + numBlocks * 5 + 4;
46
+ const out = new Uint8Array(57 + idatDataLen);
47
+ const dv = new DataView(out.buffer);
48
+ out.set([
49
+ 137,
50
+ 80,
51
+ 78,
52
+ 71,
53
+ 13,
54
+ 10,
55
+ 26,
56
+ 10
57
+ ], 0);
58
+ dv.setUint32(8, 13, false);
59
+ out.set([
60
+ 73,
61
+ 72,
62
+ 68,
63
+ 82
64
+ ], 12);
65
+ dv.setUint32(16, width, false);
66
+ dv.setUint32(20, height, false);
67
+ out[24] = 8;
68
+ out[25] = 6;
69
+ out[26] = 0;
70
+ out[27] = 0;
71
+ out[28] = 0;
72
+ dv.setUint32(29, pngCrc32(out, 12, 17), false);
73
+ dv.setUint32(33, idatDataLen, false);
74
+ out.set([
75
+ 73,
76
+ 68,
77
+ 65,
78
+ 84
79
+ ], 37);
80
+ let p = 41;
81
+ out[p++] = 120;
82
+ out[p++] = 1;
83
+ let rem = rawLen;
84
+ let rOff = 0;
85
+ while (rem > 0 || rOff === 0) {
86
+ const chunk = Math.min(65535, rem);
87
+ const isFinal = rem - chunk <= 0 ? 1 : 0;
88
+ out[p++] = isFinal;
89
+ out[p++] = chunk & 255;
90
+ out[p++] = chunk >>> 8 & 255;
91
+ const nlen = ~chunk & 65535;
92
+ out[p++] = nlen & 255;
93
+ out[p++] = nlen >>> 8 & 255;
94
+ if (chunk > 0) {
95
+ out.set(raw.subarray(rOff, rOff + chunk), p);
96
+ p += chunk;
97
+ rOff += chunk;
98
+ rem -= chunk;
99
+ }
100
+ if (isFinal) break;
101
+ }
102
+ dv.setUint32(p, adler, false);
103
+ p += 4;
104
+ dv.setUint32(p, pngCrc32(out, 37, 4 + idatDataLen), false);
105
+ p += 4;
106
+ dv.setUint32(p, 0, false);
107
+ out.set([
108
+ 73,
109
+ 69,
110
+ 78,
111
+ 68
112
+ ], p + 4);
113
+ dv.setUint32(p + 8, pngCrc32(out, p + 4, 4), false);
114
+ return out;
115
+ }
116
+ function createGpuStubCanvas(width, height) {
117
+ return {
118
+ width,
119
+ height,
120
+ getContext() {
121
+ return null;
122
+ }
123
+ };
124
+ }
6
125
  function createVirtualDomHost(createCanvas, width, height) {
7
126
  const winStub = {
8
127
  innerWidth: width,
@@ -72,8 +191,9 @@ function createHeadlessStage(options) {
72
191
  const height = Math.max(1, Math.round(options.height ?? 720));
73
192
  const fps = Math.max(1, Math.min(240, options.fps ?? 60));
74
193
  const dt = 1e3 / fps;
194
+ if (!options.createCanvas && !options.gpuDevice && !options.glContext) throw new Error("createHeadlessStage: pass createCanvas (e.g. from @napi-rs/canvas) for Canvas2D, or use await createHeadlessStageAsync({ renderer: \"webgpu\" | \"auto\", ... })");
75
195
  if (options.Path2D && typeof globalThis.Path2D !== "function") globalThis.Path2D = options.Path2D;
76
- const { rootCanvas } = createVirtualDomHost(options.createCanvas, width, height);
196
+ const { rootCanvas } = createVirtualDomHost(options.createCanvas ?? createGpuStubCanvas, width, height);
77
197
  const game = new Game({
78
198
  type: options.gpuDevice ? 3 : options.glContext ? 2 : 1,
79
199
  canvas: rootCanvas,
@@ -182,20 +302,28 @@ function createHeadlessStage(options) {
182
302
  return toRgba();
183
303
  };
184
304
  const toPng = () => {
185
- if (game.renderer.type !== 1) syncGpuPixelsToRootCanvas(toRgba());
305
+ const cw = rootCanvas.width || width;
306
+ const ch = rootCanvas.height || height;
307
+ const rgba = game.renderer.type !== 1 ? toRgba() : null;
308
+ if (rgba) syncGpuPixelsToRootCanvas(rgba);
186
309
  if (typeof rootCanvas.toBuffer === "function") {
187
310
  const buf = rootCanvas.toBuffer("image/png");
188
311
  return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
189
312
  }
190
- throw new Error("HeadlessStage.toPng: canvas does not implement toBuffer(\"image/png\"); pass createCanvas from @napi-rs/canvas");
313
+ if (rgba) return encodeRgbaToPngFallback(rgba, cw, ch);
314
+ return encodeRgbaToPngFallback(toRgba(), cw, ch);
191
315
  };
192
316
  const toPngAsync = async () => {
193
- if (game.renderer.type !== 1) syncGpuPixelsToRootCanvas(await toRgbaAsync());
317
+ const cw = rootCanvas.width || width;
318
+ const ch = rootCanvas.height || height;
319
+ const rgba = game.renderer.type !== 1 ? await toRgbaAsync() : null;
320
+ if (rgba) syncGpuPixelsToRootCanvas(rgba);
194
321
  if (typeof rootCanvas.toBuffer === "function") {
195
322
  const buf = rootCanvas.toBuffer("image/png");
196
323
  return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
197
324
  }
198
- throw new Error("HeadlessStage.toPngAsync: canvas does not implement toBuffer(\"image/png\"); pass createCanvas from @napi-rs/canvas");
325
+ if (rgba) return encodeRgbaToPngFallback(rgba, cw, ch);
326
+ return encodeRgbaToPngFallback(await toRgbaAsync(), cw, ch);
199
327
  };
200
328
  const digest = (digestOpts) => buildSceneDigest(primaryScene, digestOpts);
201
329
  const recordFrames = async (recOpts) => {
@@ -232,6 +360,7 @@ function createHeadlessStage(options) {
232
360
  game,
233
361
  scene: primaryScene,
234
362
  canvas: rootCanvas,
363
+ backend: options.backend ?? (game.renderer.type === 3 ? "webgpu" : game.renderer.type === 2 ? "webgl" : "canvas2d"),
235
364
  width,
236
365
  height,
237
366
  fps,
@@ -281,10 +410,73 @@ function createHeadlessStage(options) {
281
410
  digest,
282
411
  recordFrames,
283
412
  encodeVideo: (encOpts) => encodeVideoWithFfmpeg(self, encOpts),
284
- destroy: () => game.destroy(false)
413
+ destroy: () => {
414
+ game.destroy(false);
415
+ options.onDestroy?.();
416
+ }
285
417
  };
286
418
  return self;
287
419
  }
420
+ const dynamicImportHeadless = (specifier) => import(
421
+ /* @vite-ignore */
422
+ specifier
423
+ );
424
+ async function tryAutoDiscoverCanvasFactory() {
425
+ try {
426
+ const mod = await dynamicImportHeadless("@napi-rs/canvas");
427
+ if (mod && typeof mod.createCanvas === "function") return {
428
+ createCanvas: mod.createCanvas,
429
+ Path2D: mod.Path2D
430
+ };
431
+ } catch {}
432
+ const proc = globalThis.process;
433
+ if (!proc || typeof proc.cwd !== "function") return {};
434
+ try {
435
+ const [modNs, pathNs] = await Promise.all([dynamicImportHeadless("node:module"), dynamicImportHeadless("node:path")]);
436
+ const mod = modNs.createRequire(pathNs.join(proc.cwd(), "__stage_canvas_resolve__.cjs"))("@napi-rs/canvas");
437
+ if (mod && typeof mod.createCanvas === "function") return {
438
+ createCanvas: mod.createCanvas,
439
+ Path2D: mod.Path2D
440
+ };
441
+ } catch {}
442
+ return {};
443
+ }
444
+ /**
445
+ * Turnkey async headless Stage initializer across **Bun**, **Node.js**, and **Deno**:
446
+ * - Automatically discovers native Headless WebGPU (`wgpu-native` FFI -> Dawn `webgpu` -> `navigator.gpu`) when `renderer` is `'auto'` (default) or `'webgpu'`
447
+ * - Automatically discovers `@napi-rs/canvas` (`createCanvas` & `Path2D`) if installed when `createCanvas` is omitted (and runs pure-GPU scenes with zero npm dependencies!)
448
+ * - Manages `GPUDevice` cleanup automatically inside `stage.destroy()` and exposes the active backend via `stage.backend`
449
+ */
450
+ async function createHeadlessStageAsync(options) {
451
+ const mode = options.renderer ?? "auto";
452
+ let createCanvas = options.createCanvas;
453
+ let path2DCtor = options.Path2D;
454
+ if (!createCanvas) {
455
+ const discovered = await tryAutoDiscoverCanvasFactory();
456
+ createCanvas = discovered.createCanvas;
457
+ if (!path2DCtor && discovered.Path2D) path2DCtor = discovered.Path2D;
458
+ }
459
+ let gpu = null;
460
+ if (mode === "webgpu" || mode === "auto") {
461
+ gpu = await requestHeadlessWebGpu(options.webgpu);
462
+ if (!gpu && mode === "webgpu") throw new Error("createHeadlessStageAsync: WebGPU requested (renderer: \"webgpu\") but no native WebGPU backend was found. Set STAGE_WGPU_LIB=/path/to/libwgpu_native.{so,dylib,dll}, install the \"webgpu\" (Dawn) package, run on Deno with --unstable-webgpu, or pass renderer: \"auto\" to allow Canvas2D fallback.");
463
+ }
464
+ if (!gpu && !options.glContext && !createCanvas) throw new Error("createHeadlessStageAsync: neither a Headless WebGPU backend nor @napi-rs/canvas was found; install @napi-rs/canvas or configure WebGPU.");
465
+ return createHeadlessStage({
466
+ ...options,
467
+ createCanvas,
468
+ Path2D: path2DCtor,
469
+ gpuDevice: gpu?.device ?? null,
470
+ gpuFormat: gpu?.format,
471
+ backend: gpu ? gpu.backend : options.glContext ? "webgl" : "canvas2d",
472
+ onDestroy: () => {
473
+ options.onDestroy?.();
474
+ gpu?.destroy();
475
+ }
476
+ });
477
+ }
478
+ /** Alias for `createHeadlessStageAsync` (`await openHeadlessStage({ renderer: 'webgpu', scene })`). */
479
+ const openHeadlessStage = createHeadlessStageAsync;
288
480
  /**
289
481
  * Step a `HeadlessStage` across target keyframes and composite a single multi-panel
290
482
  * storyboard contact sheet + paired `SceneDigest` array so AI agents can visually and
@@ -436,40 +628,998 @@ function createAudioTimeline(options = {}) {
436
628
  };
437
629
  }
438
630
  /**
439
- * Build deterministic `ffmpeg` CLI arguments that consume raw `RGBA8888` frames from `stdin` (`pipe:0`),
440
- * bypassing per-frame PNG/JPEG `image2pipe` CPU encoding overhead (~33 ms/frame saved at 1280x720!).
631
+ * Build deterministic `ffmpeg` CLI arguments that consume `rawvideo` (`RGBA8888`), `mjpeg`, or `png` frames from `stdin` (`pipe:0`),
632
+ * adapting container flags automatically for MP4 (`libx264` + `+faststart`) and WebM (`libvpx-vp9`).
441
633
  */
442
634
  function buildFfmpegRawVideoArgs(options) {
443
635
  const w = Math.max(1, Math.round(options.width));
444
636
  const h = Math.max(1, Math.round(options.height));
445
637
  const fps = Math.max(1, Math.round(options.fps));
446
- const args = [
447
- "-y",
448
- "-f",
449
- "rawvideo",
450
- "-pix_fmt",
451
- "rgba",
452
- "-s",
453
- `${w}x${h}`,
454
- "-r",
455
- String(fps),
456
- "-i",
457
- "pipe:0"
458
- ];
638
+ const inFmt = options.inputFormat ?? "rawvideo";
639
+ const isWebm = /\.webm$/i.test(options.outputPath);
640
+ const vCodec = options.videoCodec ?? (isWebm ? "libvpx-vp9" : "libx264");
641
+ const isVp9 = vCodec.includes("vp9") || vCodec.includes("vp8");
642
+ const args = ["-y"];
643
+ if (inFmt === "mjpeg" || inFmt === "png") args.push("-f", "image2pipe", "-vcodec", inFmt, "-r", String(fps), "-i", "pipe:0");
644
+ else args.push("-f", "rawvideo", "-pix_fmt", "rgba", "-s", `${w}x${h}`, "-r", String(fps), "-i", "pipe:0");
459
645
  if (options.audioWavPath) args.push("-i", options.audioWavPath);
460
- args.push("-c:v", options.videoCodec ?? "libx264", "-preset", options.preset ?? "veryfast", "-crf", String(options.crf ?? 19), "-pix_fmt", options.outputPixelFormat ?? "yuv420p");
461
- if (options.audioWavPath) args.push("-c:a", options.audioCodec ?? "aac", "-b:a", options.audioBitrate ?? "160k", "-shortest");
646
+ args.push("-c:v", vCodec);
647
+ if (isVp9) args.push("-b:v", "0", "-crf", String(options.crf ?? 28), "-deadline", "realtime", "-cpu-used", "8", "-pix_fmt", options.outputPixelFormat ?? "yuv420p");
648
+ else {
649
+ if (options.preset !== "") args.push("-preset", options.preset ?? "veryfast");
650
+ args.push("-crf", String(options.crf ?? 19), "-pix_fmt", options.outputPixelFormat ?? "yuv420p");
651
+ }
652
+ if (options.audioWavPath) args.push("-c:a", options.audioCodec ?? (isWebm ? "libopus" : "aac"), "-b:a", options.audioBitrate ?? "160k", "-shortest");
462
653
  if (options.extraArgs && options.extraArgs.length > 0) args.push(...options.extraArgs);
463
- args.push("-movflags", "+faststart", options.outputPath);
654
+ if (isWebm || isVp9) {
655
+ if (isWebm) args.push("-f", "webm");
656
+ args.push(options.outputPath);
657
+ } else args.push("-movflags", "+faststart", options.outputPath);
464
658
  return args;
465
659
  }
660
+ const JPEG_ZIGZAG = new Uint8Array([
661
+ 0,
662
+ 1,
663
+ 8,
664
+ 16,
665
+ 9,
666
+ 2,
667
+ 3,
668
+ 10,
669
+ 17,
670
+ 24,
671
+ 32,
672
+ 25,
673
+ 18,
674
+ 11,
675
+ 4,
676
+ 5,
677
+ 12,
678
+ 19,
679
+ 26,
680
+ 33,
681
+ 40,
682
+ 48,
683
+ 41,
684
+ 34,
685
+ 27,
686
+ 20,
687
+ 13,
688
+ 6,
689
+ 7,
690
+ 14,
691
+ 21,
692
+ 28,
693
+ 35,
694
+ 42,
695
+ 49,
696
+ 56,
697
+ 57,
698
+ 50,
699
+ 43,
700
+ 36,
701
+ 29,
702
+ 22,
703
+ 15,
704
+ 23,
705
+ 30,
706
+ 37,
707
+ 44,
708
+ 51,
709
+ 58,
710
+ 59,
711
+ 52,
712
+ 45,
713
+ 38,
714
+ 31,
715
+ 39,
716
+ 46,
717
+ 53,
718
+ 60,
719
+ 61,
720
+ 54,
721
+ 47,
722
+ 55,
723
+ 62,
724
+ 63
725
+ ]);
726
+ const JPEG_STD_LUM_Q = new Uint8Array([
727
+ 16,
728
+ 11,
729
+ 10,
730
+ 16,
731
+ 24,
732
+ 40,
733
+ 51,
734
+ 61,
735
+ 12,
736
+ 12,
737
+ 14,
738
+ 19,
739
+ 26,
740
+ 58,
741
+ 60,
742
+ 55,
743
+ 14,
744
+ 13,
745
+ 16,
746
+ 24,
747
+ 40,
748
+ 57,
749
+ 69,
750
+ 56,
751
+ 14,
752
+ 17,
753
+ 22,
754
+ 29,
755
+ 51,
756
+ 87,
757
+ 80,
758
+ 62,
759
+ 18,
760
+ 22,
761
+ 37,
762
+ 56,
763
+ 68,
764
+ 109,
765
+ 103,
766
+ 77,
767
+ 24,
768
+ 35,
769
+ 55,
770
+ 64,
771
+ 81,
772
+ 104,
773
+ 113,
774
+ 92,
775
+ 49,
776
+ 64,
777
+ 78,
778
+ 87,
779
+ 103,
780
+ 121,
781
+ 120,
782
+ 101,
783
+ 72,
784
+ 92,
785
+ 95,
786
+ 98,
787
+ 112,
788
+ 100,
789
+ 103,
790
+ 99
791
+ ]);
792
+ const JPEG_STD_CHR_Q = new Uint8Array([
793
+ 17,
794
+ 18,
795
+ 24,
796
+ 47,
797
+ 99,
798
+ 99,
799
+ 99,
800
+ 99,
801
+ 18,
802
+ 21,
803
+ 26,
804
+ 66,
805
+ 99,
806
+ 99,
807
+ 99,
808
+ 99,
809
+ 24,
810
+ 26,
811
+ 56,
812
+ 99,
813
+ 99,
814
+ 99,
815
+ 99,
816
+ 99,
817
+ 47,
818
+ 66,
819
+ 99,
820
+ 99,
821
+ 99,
822
+ 99,
823
+ 99,
824
+ 99,
825
+ 99,
826
+ 99,
827
+ 99,
828
+ 99,
829
+ 99,
830
+ 99,
831
+ 99,
832
+ 99,
833
+ 99,
834
+ 99,
835
+ 99,
836
+ 99,
837
+ 99,
838
+ 99,
839
+ 99,
840
+ 99,
841
+ 99,
842
+ 99,
843
+ 99,
844
+ 99,
845
+ 99,
846
+ 99,
847
+ 99,
848
+ 99,
849
+ 99,
850
+ 99,
851
+ 99,
852
+ 99,
853
+ 99,
854
+ 99,
855
+ 99,
856
+ 99
857
+ ]);
858
+ const JPEG_DC_LUM_NRCODES = new Uint8Array([
859
+ 0,
860
+ 0,
861
+ 1,
862
+ 5,
863
+ 1,
864
+ 1,
865
+ 1,
866
+ 1,
867
+ 1,
868
+ 1,
869
+ 0,
870
+ 0,
871
+ 0,
872
+ 0,
873
+ 0,
874
+ 0,
875
+ 0
876
+ ]);
877
+ const JPEG_DC_LUM_VALS = new Uint8Array([
878
+ 0,
879
+ 1,
880
+ 2,
881
+ 3,
882
+ 4,
883
+ 5,
884
+ 6,
885
+ 7,
886
+ 8,
887
+ 9,
888
+ 10,
889
+ 11
890
+ ]);
891
+ const JPEG_DC_CHR_NRCODES = new Uint8Array([
892
+ 0,
893
+ 0,
894
+ 3,
895
+ 1,
896
+ 1,
897
+ 1,
898
+ 1,
899
+ 1,
900
+ 1,
901
+ 1,
902
+ 1,
903
+ 1,
904
+ 0,
905
+ 0,
906
+ 0,
907
+ 0,
908
+ 0
909
+ ]);
910
+ const JPEG_DC_CHR_VALS = new Uint8Array([
911
+ 0,
912
+ 1,
913
+ 2,
914
+ 3,
915
+ 4,
916
+ 5,
917
+ 6,
918
+ 7,
919
+ 8,
920
+ 9,
921
+ 10,
922
+ 11
923
+ ]);
924
+ const JPEG_AC_LUM_NRCODES = new Uint8Array([
925
+ 0,
926
+ 0,
927
+ 2,
928
+ 1,
929
+ 3,
930
+ 3,
931
+ 2,
932
+ 4,
933
+ 3,
934
+ 5,
935
+ 5,
936
+ 4,
937
+ 4,
938
+ 0,
939
+ 0,
940
+ 1,
941
+ 125
942
+ ]);
943
+ const JPEG_AC_LUM_VALS = new Uint8Array([
944
+ 1,
945
+ 2,
946
+ 3,
947
+ 0,
948
+ 4,
949
+ 17,
950
+ 5,
951
+ 18,
952
+ 33,
953
+ 49,
954
+ 65,
955
+ 6,
956
+ 19,
957
+ 81,
958
+ 97,
959
+ 7,
960
+ 34,
961
+ 113,
962
+ 20,
963
+ 50,
964
+ 129,
965
+ 145,
966
+ 161,
967
+ 8,
968
+ 35,
969
+ 66,
970
+ 177,
971
+ 193,
972
+ 21,
973
+ 82,
974
+ 209,
975
+ 240,
976
+ 36,
977
+ 51,
978
+ 98,
979
+ 114,
980
+ 130,
981
+ 9,
982
+ 10,
983
+ 22,
984
+ 23,
985
+ 24,
986
+ 25,
987
+ 26,
988
+ 37,
989
+ 38,
990
+ 39,
991
+ 40,
992
+ 41,
993
+ 42,
994
+ 52,
995
+ 53,
996
+ 54,
997
+ 55,
998
+ 56,
999
+ 57,
1000
+ 58,
1001
+ 67,
1002
+ 68,
1003
+ 69,
1004
+ 70,
1005
+ 71,
1006
+ 72,
1007
+ 73,
1008
+ 74,
1009
+ 83,
1010
+ 84,
1011
+ 85,
1012
+ 86,
1013
+ 87,
1014
+ 88,
1015
+ 89,
1016
+ 90,
1017
+ 99,
1018
+ 100,
1019
+ 101,
1020
+ 102,
1021
+ 103,
1022
+ 104,
1023
+ 105,
1024
+ 106,
1025
+ 115,
1026
+ 116,
1027
+ 117,
1028
+ 118,
1029
+ 119,
1030
+ 120,
1031
+ 121,
1032
+ 122,
1033
+ 131,
1034
+ 132,
1035
+ 133,
1036
+ 134,
1037
+ 135,
1038
+ 136,
1039
+ 137,
1040
+ 138,
1041
+ 146,
1042
+ 147,
1043
+ 148,
1044
+ 149,
1045
+ 150,
1046
+ 151,
1047
+ 152,
1048
+ 153,
1049
+ 154,
1050
+ 162,
1051
+ 163,
1052
+ 164,
1053
+ 165,
1054
+ 166,
1055
+ 167,
1056
+ 168,
1057
+ 169,
1058
+ 170,
1059
+ 178,
1060
+ 179,
1061
+ 180,
1062
+ 181,
1063
+ 182,
1064
+ 183,
1065
+ 184,
1066
+ 185,
1067
+ 186,
1068
+ 194,
1069
+ 195,
1070
+ 196,
1071
+ 197,
1072
+ 198,
1073
+ 199,
1074
+ 200,
1075
+ 201,
1076
+ 202,
1077
+ 210,
1078
+ 211,
1079
+ 212,
1080
+ 213,
1081
+ 214,
1082
+ 215,
1083
+ 216,
1084
+ 217,
1085
+ 218,
1086
+ 225,
1087
+ 226,
1088
+ 227,
1089
+ 228,
1090
+ 229,
1091
+ 230,
1092
+ 231,
1093
+ 232,
1094
+ 233,
1095
+ 234,
1096
+ 241,
1097
+ 242,
1098
+ 243,
1099
+ 244,
1100
+ 245,
1101
+ 246,
1102
+ 247,
1103
+ 248,
1104
+ 249,
1105
+ 250
1106
+ ]);
1107
+ const JPEG_AC_CHR_NRCODES = new Uint8Array([
1108
+ 0,
1109
+ 0,
1110
+ 2,
1111
+ 1,
1112
+ 2,
1113
+ 4,
1114
+ 4,
1115
+ 3,
1116
+ 4,
1117
+ 7,
1118
+ 5,
1119
+ 4,
1120
+ 4,
1121
+ 0,
1122
+ 1,
1123
+ 2,
1124
+ 119
1125
+ ]);
1126
+ const JPEG_AC_CHR_VALS = new Uint8Array([
1127
+ 0,
1128
+ 1,
1129
+ 2,
1130
+ 3,
1131
+ 17,
1132
+ 4,
1133
+ 5,
1134
+ 33,
1135
+ 49,
1136
+ 6,
1137
+ 18,
1138
+ 65,
1139
+ 81,
1140
+ 7,
1141
+ 97,
1142
+ 113,
1143
+ 19,
1144
+ 34,
1145
+ 50,
1146
+ 129,
1147
+ 8,
1148
+ 20,
1149
+ 66,
1150
+ 145,
1151
+ 161,
1152
+ 177,
1153
+ 193,
1154
+ 9,
1155
+ 35,
1156
+ 51,
1157
+ 82,
1158
+ 240,
1159
+ 21,
1160
+ 98,
1161
+ 114,
1162
+ 209,
1163
+ 10,
1164
+ 22,
1165
+ 36,
1166
+ 52,
1167
+ 225,
1168
+ 37,
1169
+ 241,
1170
+ 23,
1171
+ 24,
1172
+ 25,
1173
+ 26,
1174
+ 38,
1175
+ 39,
1176
+ 40,
1177
+ 41,
1178
+ 42,
1179
+ 53,
1180
+ 54,
1181
+ 55,
1182
+ 56,
1183
+ 57,
1184
+ 58,
1185
+ 67,
1186
+ 68,
1187
+ 69,
1188
+ 70,
1189
+ 71,
1190
+ 72,
1191
+ 73,
1192
+ 74,
1193
+ 83,
1194
+ 84,
1195
+ 85,
1196
+ 86,
1197
+ 87,
1198
+ 88,
1199
+ 89,
1200
+ 90,
1201
+ 99,
1202
+ 100,
1203
+ 101,
1204
+ 102,
1205
+ 103,
1206
+ 104,
1207
+ 105,
1208
+ 106,
1209
+ 115,
1210
+ 116,
1211
+ 117,
1212
+ 118,
1213
+ 119,
1214
+ 120,
1215
+ 121,
1216
+ 122,
1217
+ 130,
1218
+ 131,
1219
+ 132,
1220
+ 133,
1221
+ 134,
1222
+ 135,
1223
+ 136,
1224
+ 137,
1225
+ 138,
1226
+ 146,
1227
+ 147,
1228
+ 148,
1229
+ 149,
1230
+ 150,
1231
+ 151,
1232
+ 152,
1233
+ 153,
1234
+ 154,
1235
+ 162,
1236
+ 163,
1237
+ 164,
1238
+ 165,
1239
+ 166,
1240
+ 167,
1241
+ 168,
1242
+ 169,
1243
+ 170,
1244
+ 178,
1245
+ 179,
1246
+ 180,
1247
+ 181,
1248
+ 182,
1249
+ 183,
1250
+ 184,
1251
+ 185,
1252
+ 186,
1253
+ 194,
1254
+ 195,
1255
+ 196,
1256
+ 197,
1257
+ 198,
1258
+ 199,
1259
+ 200,
1260
+ 201,
1261
+ 202,
1262
+ 210,
1263
+ 211,
1264
+ 212,
1265
+ 213,
1266
+ 214,
1267
+ 215,
1268
+ 216,
1269
+ 217,
1270
+ 218,
1271
+ 226,
1272
+ 227,
1273
+ 228,
1274
+ 229,
1275
+ 230,
1276
+ 231,
1277
+ 232,
1278
+ 233,
1279
+ 234,
1280
+ 242,
1281
+ 243,
1282
+ 244,
1283
+ 245,
1284
+ 246,
1285
+ 247,
1286
+ 248,
1287
+ 249,
1288
+ 250
1289
+ ]);
1290
+ function buildJpegHuffTable(nrcodes, vals) {
1291
+ const code = /* @__PURE__ */ new Uint16Array(256);
1292
+ const len = /* @__PURE__ */ new Uint8Array(256);
1293
+ let p = 0;
1294
+ let c = 0;
1295
+ for (let l = 1; l <= 16; l++) {
1296
+ for (let i = 0; i < nrcodes[l]; i++) {
1297
+ const sym = vals[p++];
1298
+ code[sym] = c++;
1299
+ len[sym] = l;
1300
+ }
1301
+ c <<= 1;
1302
+ }
1303
+ return {
1304
+ code,
1305
+ len
1306
+ };
1307
+ }
1308
+ let jpegTablesCache = null;
1309
+ function getJpegStaticTables() {
1310
+ if (jpegTablesCache) return jpegTablesCache;
1311
+ const cos = /* @__PURE__ */ new Float32Array(64);
1312
+ for (let u = 0; u < 8; u++) {
1313
+ const cu = u === 0 ? 1 / Math.SQRT2 : 1;
1314
+ for (let x = 0; x < 8; x++) cos[u * 8 + x] = .5 * cu * Math.cos((2 * x + 1) * u * Math.PI / 16);
1315
+ }
1316
+ jpegTablesCache = {
1317
+ dcLum: buildJpegHuffTable(JPEG_DC_LUM_NRCODES, JPEG_DC_LUM_VALS),
1318
+ dcChr: buildJpegHuffTable(JPEG_DC_CHR_NRCODES, JPEG_DC_CHR_VALS),
1319
+ acLum: buildJpegHuffTable(JPEG_AC_LUM_NRCODES, JPEG_AC_LUM_VALS),
1320
+ acChr: buildJpegHuffTable(JPEG_AC_CHR_NRCODES, JPEG_AC_CHR_VALS),
1321
+ cos
1322
+ };
1323
+ return jpegTablesCache;
1324
+ }
1325
+ /** Zero-dependency pure-TS RGBA8888 -> Baseline 4:4:4 JFIF JPEG encoder (fallback when `@napi-rs/canvas` is absent). */
1326
+ function encodeRgbaToJpegFallback(rgba, width, height, quality = 90) {
1327
+ const tables = getJpegStaticTables();
1328
+ const qClamped = Math.max(1, Math.min(100, Math.round(quality)));
1329
+ const scale = qClamped < 50 ? Math.floor(5e3 / qClamped) : 200 - qClamped * 2;
1330
+ const dqtLum = /* @__PURE__ */ new Uint8Array(64);
1331
+ const dqtChr = /* @__PURE__ */ new Uint8Array(64);
1332
+ const invLum = /* @__PURE__ */ new Float32Array(64);
1333
+ const invChr = /* @__PURE__ */ new Float32Array(64);
1334
+ for (let i = 0; i < 64; i++) {
1335
+ const ql = Math.max(1, Math.min(255, Math.floor((JPEG_STD_LUM_Q[i] * scale + 50) / 100)));
1336
+ const qc = Math.max(1, Math.min(255, Math.floor((JPEG_STD_CHR_Q[i] * scale + 50) / 100)));
1337
+ dqtLum[JPEG_ZIGZAG[i]] = ql;
1338
+ dqtChr[JPEG_ZIGZAG[i]] = qc;
1339
+ invLum[i] = 1 / ql;
1340
+ invChr[i] = 1 / qc;
1341
+ }
1342
+ let cap = Math.max(4096, width * height + 1024);
1343
+ let out = new Uint8Array(cap);
1344
+ let pos = 0;
1345
+ const ensure = (extra) => {
1346
+ if (pos + extra <= cap) return;
1347
+ while (pos + extra > cap) cap *= 2;
1348
+ const next = new Uint8Array(cap);
1349
+ next.set(out.subarray(0, pos));
1350
+ out = next;
1351
+ };
1352
+ const pushByte = (b) => {
1353
+ if (pos >= cap) ensure(64);
1354
+ out[pos++] = b & 255;
1355
+ };
1356
+ const pushU16 = (v) => {
1357
+ ensure(2);
1358
+ out[pos++] = v >>> 8 & 255;
1359
+ out[pos++] = v & 255;
1360
+ };
1361
+ const pushArr = (arr) => {
1362
+ ensure(arr.length);
1363
+ for (let i = 0; i < arr.length; i++) out[pos++] = arr[i];
1364
+ };
1365
+ pushArr([
1366
+ 255,
1367
+ 216,
1368
+ 255,
1369
+ 224,
1370
+ 0,
1371
+ 16,
1372
+ 74,
1373
+ 70,
1374
+ 73,
1375
+ 70,
1376
+ 0,
1377
+ 1,
1378
+ 1,
1379
+ 0,
1380
+ 0,
1381
+ 1,
1382
+ 0,
1383
+ 1,
1384
+ 0,
1385
+ 0
1386
+ ]);
1387
+ pushArr([
1388
+ 255,
1389
+ 219,
1390
+ 0,
1391
+ 132,
1392
+ 0
1393
+ ]);
1394
+ pushArr(dqtLum);
1395
+ pushByte(1);
1396
+ pushArr(dqtChr);
1397
+ pushArr([
1398
+ 255,
1399
+ 192,
1400
+ 0,
1401
+ 17,
1402
+ 8
1403
+ ]);
1404
+ pushU16(height);
1405
+ pushU16(width);
1406
+ pushArr([
1407
+ 3,
1408
+ 1,
1409
+ 17,
1410
+ 0,
1411
+ 2,
1412
+ 17,
1413
+ 1,
1414
+ 3,
1415
+ 17,
1416
+ 1
1417
+ ]);
1418
+ const dhtLen = 2 + (17 + JPEG_DC_LUM_VALS.length) + (17 + JPEG_AC_LUM_VALS.length) + (17 + JPEG_DC_CHR_VALS.length) + (17 + JPEG_AC_CHR_VALS.length);
1419
+ pushArr([255, 196]);
1420
+ pushU16(dhtLen);
1421
+ pushByte(0);
1422
+ pushArr(JPEG_DC_LUM_NRCODES.subarray(1));
1423
+ pushArr(JPEG_DC_LUM_VALS);
1424
+ pushByte(16);
1425
+ pushArr(JPEG_AC_LUM_NRCODES.subarray(1));
1426
+ pushArr(JPEG_AC_LUM_VALS);
1427
+ pushByte(1);
1428
+ pushArr(JPEG_DC_CHR_NRCODES.subarray(1));
1429
+ pushArr(JPEG_DC_CHR_VALS);
1430
+ pushByte(17);
1431
+ pushArr(JPEG_AC_CHR_NRCODES.subarray(1));
1432
+ pushArr(JPEG_AC_CHR_VALS);
1433
+ pushArr([
1434
+ 255,
1435
+ 218,
1436
+ 0,
1437
+ 12,
1438
+ 3,
1439
+ 1,
1440
+ 0,
1441
+ 2,
1442
+ 17,
1443
+ 3,
1444
+ 17,
1445
+ 0,
1446
+ 63,
1447
+ 0
1448
+ ]);
1449
+ let bitBuf = 0;
1450
+ let bitCnt = 0;
1451
+ const writeBits = (val, nbits) => {
1452
+ bitBuf = bitBuf << nbits | val & (1 << nbits) - 1;
1453
+ bitCnt += nbits;
1454
+ while (bitCnt >= 8) {
1455
+ bitCnt -= 8;
1456
+ const b = bitBuf >>> bitCnt & 255;
1457
+ pushByte(b);
1458
+ if (b === 255) pushByte(0);
1459
+ }
1460
+ };
1461
+ const blkY = /* @__PURE__ */ new Float32Array(64);
1462
+ const blkCb = /* @__PURE__ */ new Float32Array(64);
1463
+ const blkCr = /* @__PURE__ */ new Float32Array(64);
1464
+ const tmp = /* @__PURE__ */ new Float32Array(64);
1465
+ const qzz = /* @__PURE__ */ new Int32Array(64);
1466
+ const cos = tables.cos;
1467
+ const encodeBlock = (blk, invQ, prevDc, dcT, acT) => {
1468
+ for (let r = 0; r < 8; r++) {
1469
+ const rOff = r * 8;
1470
+ for (let u = 0; u < 8; u++) {
1471
+ const uOff = u * 8;
1472
+ tmp[rOff + u] = blk[rOff] * cos[uOff] + blk[rOff + 1] * cos[uOff + 1] + blk[rOff + 2] * cos[uOff + 2] + blk[rOff + 3] * cos[uOff + 3] + blk[rOff + 4] * cos[uOff + 4] + blk[rOff + 5] * cos[uOff + 5] + blk[rOff + 6] * cos[uOff + 6] + blk[rOff + 7] * cos[uOff + 7];
1473
+ }
1474
+ }
1475
+ for (let u = 0; u < 8; u++) for (let v = 0; v < 8; v++) {
1476
+ const vOff = v * 8;
1477
+ const val = tmp[u] * cos[vOff] + tmp[8 + u] * cos[vOff + 1] + tmp[16 + u] * cos[vOff + 2] + tmp[24 + u] * cos[vOff + 3] + tmp[32 + u] * cos[vOff + 4] + tmp[40 + u] * cos[vOff + 5] + tmp[48 + u] * cos[vOff + 6] + tmp[56 + u] * cos[vOff + 7];
1478
+ const idx = v * 8 + u;
1479
+ qzz[JPEG_ZIGZAG[idx]] = Math.round(val * invQ[idx]);
1480
+ }
1481
+ const dc = qzz[0];
1482
+ const diff = dc - prevDc;
1483
+ if (diff === 0) writeBits(dcT.code[0], dcT.len[0]);
1484
+ else {
1485
+ const absD = diff < 0 ? -diff : diff;
1486
+ const cat = 32 - Math.clz32(absD);
1487
+ writeBits(dcT.code[cat], dcT.len[cat]);
1488
+ writeBits(diff < 0 ? diff - 1 : diff, cat);
1489
+ }
1490
+ let end0 = 63;
1491
+ while (end0 > 0 && qzz[end0] === 0) end0--;
1492
+ if (end0 === 0) {
1493
+ writeBits(acT.code[0], acT.len[0]);
1494
+ return dc;
1495
+ }
1496
+ let i = 1;
1497
+ while (i <= end0) {
1498
+ const start = i;
1499
+ while (qzz[i] === 0 && i <= end0) i++;
1500
+ let nrZeroes = i - start;
1501
+ while (nrZeroes >= 16) {
1502
+ writeBits(acT.code[240], acT.len[240]);
1503
+ nrZeroes -= 16;
1504
+ }
1505
+ const ac = qzz[i];
1506
+ const absAc = ac < 0 ? -ac : ac;
1507
+ const cat = 32 - Math.clz32(absAc);
1508
+ const sym = nrZeroes << 4 | cat;
1509
+ writeBits(acT.code[sym], acT.len[sym]);
1510
+ writeBits(ac < 0 ? ac - 1 : ac, cat);
1511
+ i++;
1512
+ }
1513
+ if (end0 < 63) writeBits(acT.code[0], acT.len[0]);
1514
+ return dc;
1515
+ };
1516
+ let dcY = 0;
1517
+ let dcCb = 0;
1518
+ let dcCr = 0;
1519
+ for (let by = 0; by < height; by += 8) for (let bx = 0; bx < width; bx += 8) {
1520
+ let k = 0;
1521
+ for (let py = 0; py < 8; py++) {
1522
+ const rowOff = (by + py < height ? by + py : height - 1) * width * 4;
1523
+ for (let px = 0; px < 8; px++, k++) {
1524
+ const off = rowOff + (bx + px < width ? bx + px : width - 1) * 4;
1525
+ const r = rgba[off];
1526
+ const g = rgba[off + 1];
1527
+ const b = rgba[off + 2];
1528
+ blkY[k] = .299 * r + .587 * g + .114 * b - 128;
1529
+ blkCb[k] = -.168736 * r - .331264 * g + .5 * b;
1530
+ blkCr[k] = .5 * r - .418688 * g - .081312 * b;
1531
+ }
1532
+ }
1533
+ dcY = encodeBlock(blkY, invLum, dcY, tables.dcLum, tables.acLum);
1534
+ dcCb = encodeBlock(blkCb, invChr, dcCb, tables.dcChr, tables.acChr);
1535
+ dcCr = encodeBlock(blkCr, invChr, dcCr, tables.dcChr, tables.acChr);
1536
+ }
1537
+ if (bitCnt > 0) writeBits((1 << 8 - bitCnt) - 1, 8 - bitCnt);
1538
+ pushArr([255, 217]);
1539
+ return out.subarray(0, pos);
1540
+ }
1541
+ const ffmpegCapsCache = /* @__PURE__ */ new Map();
1542
+ function probeFfmpegCapabilities(cp, bin) {
1543
+ if (typeof cp.spawnSync !== "function") return null;
1544
+ if (/\.(?:m?js|cjs|ts|py)$/i.test(bin)) return null;
1545
+ const cached = ffmpegCapsCache.get(bin);
1546
+ if (cached) return cached;
1547
+ const demux = cp.spawnSync(bin, ["-hide_banner", "-demuxers"], {
1548
+ encoding: "utf8",
1549
+ timeout: 4e3
1550
+ });
1551
+ const dOut = demux.stdout ?? "";
1552
+ if (demux.error || demux.status !== 0 || !dOut.includes("Formats:")) {
1553
+ const miss = {
1554
+ found: false,
1555
+ rawvideo: false,
1556
+ image2pipe: false,
1557
+ mjpegDec: false,
1558
+ pngDec: false,
1559
+ libx264: false,
1560
+ libvpxVp9: false,
1561
+ aac: false,
1562
+ libopus: false
1563
+ };
1564
+ ffmpegCapsCache.set(bin, miss);
1565
+ return miss;
1566
+ }
1567
+ const enc = cp.spawnSync(bin, ["-hide_banner", "-encoders"], {
1568
+ encoding: "utf8",
1569
+ timeout: 4e3
1570
+ });
1571
+ const dec = cp.spawnSync(bin, ["-hide_banner", "-decoders"], {
1572
+ encoding: "utf8",
1573
+ timeout: 4e3
1574
+ });
1575
+ const eOut = enc.stdout ?? "";
1576
+ const cOut = dec.stdout ?? "";
1577
+ if (!eOut.includes("Encoders:")) return null;
1578
+ const caps = {
1579
+ found: true,
1580
+ rawvideo: /\brawvideo\b/.test(dOut),
1581
+ image2pipe: /\bimage2pipe\b/.test(dOut),
1582
+ mjpegDec: /\bmjpeg\b/.test(cOut),
1583
+ pngDec: /\bpng\b/.test(cOut),
1584
+ libx264: /\blibx264\b/.test(eOut),
1585
+ libvpxVp9: /\blibvpx-vp9\b/.test(eOut),
1586
+ aac: /\baac\b/.test(eOut),
1587
+ libopus: /\blibopus\b/.test(eOut)
1588
+ };
1589
+ ffmpegCapsCache.set(bin, caps);
1590
+ return caps;
1591
+ }
1592
+ function discoverPlaywrightFfmpeg(fs, os, path) {
1593
+ if (typeof fs.existsSync !== "function" || typeof fs.readdirSync !== "function") return null;
1594
+ const proc = globalThis.process;
1595
+ const home = typeof os.homedir === "function" ? os.homedir() : "";
1596
+ const roots = [
1597
+ proc?.env?.PLAYWRIGHT_BROWSERS_PATH,
1598
+ home ? path.join(home, ".cache", "ms-playwright") : "",
1599
+ home ? path.join(home, "Library", "Caches", "ms-playwright") : ""
1600
+ ].filter((x) => Boolean(x));
1601
+ const binNames = proc?.platform === "darwin" ? ["ffmpeg-mac"] : proc?.platform === "win32" ? ["ffmpeg-win64.exe"] : ["ffmpeg-linux"];
1602
+ for (const root of roots) {
1603
+ if (!fs.existsSync(root)) continue;
1604
+ const dirs = fs.readdirSync(root).sort().reverse();
1605
+ for (const d of dirs) {
1606
+ if (!d.startsWith("ffmpeg-")) continue;
1607
+ for (const b of binNames) {
1608
+ const candidate = path.join(root, d, b);
1609
+ if (fs.existsSync(candidate)) return candidate;
1610
+ }
1611
+ }
1612
+ }
1613
+ return null;
1614
+ }
466
1615
  const dynamicImportModule = (specifier) => import(
467
1616
  /* @vite-ignore */
468
1617
  specifier
469
1618
  );
470
1619
  /**
471
- * Step a `HeadlessStage` in Node.js or Bun and stream raw `RGBA8888` frames (`-f rawvideo -pix_fmt rgba`)
472
- * directly into `ffmpeg` stdin with backpressure handling and optional stereo `.wav` audio muxing.
1620
+ * Step a `HeadlessStage` in Node.js or Bun and stream frames into `ffmpeg` stdin with backpressure handling.
1621
+ * Automatically uses zero-copy `rawvideo` (`RGBA8888`) on full `ffmpeg` builds and falls back seamlessly to
1622
+ * `image2pipe` (`mjpeg` + `libvpx-vp9` WebM) when only Playwright's trimmed `ffmpeg` binary is available.
473
1623
  */
474
1624
  async function encodeVideoWithFfmpeg(stage, options) {
475
1625
  const [cp, fs, os, path] = await Promise.all([
@@ -482,30 +1632,46 @@ async function encodeVideoWithFfmpeg(stage, options) {
482
1632
  const durationMs = totalFrames / stage.fps * 1e3;
483
1633
  const cw = stage.canvas.width || stage.width;
484
1634
  const ch = stage.canvas.height || stage.height;
1635
+ let ffmpegBin = options.ffmpegPath ?? "ffmpeg";
1636
+ let caps = probeFfmpegCapabilities(cp, ffmpegBin);
1637
+ if (!options.ffmpegPath && caps && !caps.found) {
1638
+ const pwBin = discoverPlaywrightFfmpeg(fs, os, path);
1639
+ if (pwBin) {
1640
+ ffmpegBin = pwBin;
1641
+ caps = probeFfmpegCapabilities(cp, ffmpegBin);
1642
+ }
1643
+ }
1644
+ const isWebm = /\.webm$/i.test(options.outputPath);
1645
+ const resolvedInputFormat = options.inputFormat && options.inputFormat !== "auto" ? options.inputFormat : caps && !caps.rawvideo && caps.image2pipe ? caps.mjpegDec ? "mjpeg" : "png" : "rawvideo";
1646
+ const resolvedVideoCodec = options.videoCodec ?? (isWebm ? "libvpx-vp9" : caps?.found && !caps.libx264 && caps.libvpxVp9 ? "libvpx-vp9" : "libx264");
1647
+ const canMuxAudio = Boolean(options.audio) && (!caps?.found || Boolean(options.audioCodec) || caps.aac || caps.libopus);
485
1648
  let tempWavPath = null;
486
1649
  let audioWavPath;
487
- if (typeof options.audio === "string") audioWavPath = options.audio;
488
- else if (options.audio) {
489
- const wavBytes = options.audio instanceof Uint8Array ? options.audio : options.audio.toWav(durationMs);
490
- tempWavPath = path.join(os.tmpdir(), `holt-stage-audio-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.wav`);
491
- fs.writeFileSync(tempWavPath, wavBytes);
492
- audioWavPath = tempWavPath;
1650
+ if (canMuxAudio) {
1651
+ if (typeof options.audio === "string") audioWavPath = options.audio;
1652
+ else if (options.audio) {
1653
+ const wavBytes = options.audio instanceof Uint8Array ? options.audio : options.audio.toWav(durationMs);
1654
+ tempWavPath = path.join(os.tmpdir(), `holt-stage-audio-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.wav`);
1655
+ fs.writeFileSync(tempWavPath, wavBytes);
1656
+ audioWavPath = tempWavPath;
1657
+ }
493
1658
  }
1659
+ const resolvedAudioCodec = options.audioCodec ?? (isWebm || resolvedVideoCodec.includes("vp9") ? caps?.found && !caps.libopus && caps.aac ? "aac" : "libopus" : caps?.found && !caps.aac && caps.libopus ? "libopus" : "aac");
494
1660
  const ffArgs = buildFfmpegRawVideoArgs({
495
1661
  width: cw,
496
1662
  height: ch,
497
1663
  fps: stage.fps,
498
1664
  outputPath: options.outputPath,
1665
+ inputFormat: resolvedInputFormat,
499
1666
  audioWavPath,
500
- videoCodec: options.videoCodec,
1667
+ videoCodec: resolvedVideoCodec,
501
1668
  preset: options.preset,
502
1669
  crf: options.crf,
503
1670
  outputPixelFormat: options.outputPixelFormat,
504
- audioCodec: options.audioCodec,
1671
+ audioCodec: resolvedAudioCodec,
505
1672
  audioBitrate: options.audioBitrate,
506
1673
  extraArgs: options.extraArgs
507
1674
  });
508
- const ffmpegBin = options.ffmpegPath ?? "ffmpeg";
509
1675
  const ff = cp.spawn(ffmpegBin, ffArgs, { stdio: [
510
1676
  "pipe",
511
1677
  "ignore",
@@ -594,17 +1760,39 @@ async function encodeVideoWithFfmpeg(stage, options) {
594
1760
  ff.once("error", onProcErr);
595
1761
  ff.once("close", onProcClose);
596
1762
  });
1763
+ const jpegQuality = Math.max(1, Math.min(100, Math.round(options.jpegQuality ?? 90)));
1764
+ const encodeFramePayload = (rgba) => {
1765
+ if (resolvedInputFormat === "rawvideo") return rgba;
1766
+ const rootCanvas = stage.canvas;
1767
+ if (typeof rootCanvas.toBuffer === "function") {
1768
+ if (stage.game.renderer.type !== 1) {
1769
+ const ctx2d = rootCanvas.getContext("2d");
1770
+ if (ctx2d && typeof ctx2d.createImageData === "function" && typeof ctx2d.putImageData === "function") {
1771
+ const imgData = ctx2d.createImageData(cw, ch);
1772
+ imgData.data.set(rgba.subarray(0, cw * ch * 4));
1773
+ ctx2d.putImageData(imgData, 0, 0);
1774
+ }
1775
+ }
1776
+ try {
1777
+ const buf = resolvedInputFormat === "mjpeg" ? rootCanvas.toBuffer("image/jpeg", jpegQuality) : rootCanvas.toBuffer("image/png");
1778
+ if (buf && buf.byteLength > 0) return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
1779
+ } catch {}
1780
+ }
1781
+ return resolvedInputFormat === "mjpeg" ? encodeRgbaToJpegFallback(rgba, cw, ch, jpegQuality) : encodeRgbaToPngFallback(rgba, cw, ch);
1782
+ };
597
1783
  const clock = await stage.recordFrames({
598
1784
  frames: totalFrames,
599
1785
  digestEvery: options.digestEvery,
600
1786
  digestOptions: options.digestOptions,
1787
+ reuseFrameBuffer: !options.onFrame,
601
1788
  onFrame: async (frame) => {
602
1789
  if (frame.digest) digests.push(frame.digest);
603
1790
  if (options.onFrame) await options.onFrame(frame);
604
1791
  if (spawnError) throw spawnError;
605
1792
  if (stdinError) throw stdinError;
606
1793
  if (closed) throw new Error(`encodeVideoWithFfmpeg: ffmpeg exited early with code ${String(closedCode)}:\n${stderrLog}`);
607
- if (!ff.stdin.write(frame.rgba)) await waitDrainOrExit();
1794
+ const payload = encodeFramePayload(frame.rgba);
1795
+ if (!ff.stdin.write(payload)) await waitDrainOrExit();
608
1796
  }
609
1797
  });
610
1798
  ff.stdin.end();
@@ -619,7 +1807,9 @@ async function encodeVideoWithFfmpeg(stage, options) {
619
1807
  fps: stage.fps,
620
1808
  durationMs,
621
1809
  clock,
622
- digests
1810
+ digests,
1811
+ inputFormat: resolvedInputFormat,
1812
+ videoCodec: resolvedVideoCodec
623
1813
  };
624
1814
  } finally {
625
1815
  try {
@@ -630,4 +1820,4 @@ async function encodeVideoWithFfmpeg(stage, options) {
630
1820
  } catch {}
631
1821
  }
632
1822
  }
633
- export { buildFfmpegRawVideoArgs, createAudioTimeline, createHeadlessStage, encodeVideoWithFfmpeg, openDawnWebGpu, openWgpuNativeFfi, renderStoryboard, requestHeadlessWebGpu };
1823
+ export { buildFfmpegRawVideoArgs, createAudioTimeline, createHeadlessStage, createHeadlessStageAsync, encodeVideoWithFfmpeg, openDawnWebGpu, openHeadlessStage, openWgpuNativeFfi, renderStoryboard, requestHeadlessWebGpu };