@holtjs/stage 0.14.0 → 0.16.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,6 +1,6 @@
1
1
  import "./types-CXsCvp1p.js";
2
- import { n as Game } from "./game-BF1ZbJRC.js";
3
- import { a as requestHeadlessWebGpu, i as openWgpuNativeFfi, r as openDawnWebGpu } from "./renderer-webgpu-CnIevdNP.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
6
  let pngCrcTable = null;
@@ -628,40 +628,998 @@ function createAudioTimeline(options = {}) {
628
628
  };
629
629
  }
630
630
  /**
631
- * Build deterministic `ffmpeg` CLI arguments that consume raw `RGBA8888` frames from `stdin` (`pipe:0`),
632
- * 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`).
633
633
  */
634
634
  function buildFfmpegRawVideoArgs(options) {
635
635
  const w = Math.max(1, Math.round(options.width));
636
636
  const h = Math.max(1, Math.round(options.height));
637
637
  const fps = Math.max(1, Math.round(options.fps));
638
- const args = [
639
- "-y",
640
- "-f",
641
- "rawvideo",
642
- "-pix_fmt",
643
- "rgba",
644
- "-s",
645
- `${w}x${h}`,
646
- "-r",
647
- String(fps),
648
- "-i",
649
- "pipe:0"
650
- ];
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");
651
645
  if (options.audioWavPath) args.push("-i", options.audioWavPath);
652
- args.push("-c:v", options.videoCodec ?? "libx264", "-preset", options.preset ?? "veryfast", "-crf", String(options.crf ?? 19), "-pix_fmt", options.outputPixelFormat ?? "yuv420p");
653
- 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");
654
653
  if (options.extraArgs && options.extraArgs.length > 0) args.push(...options.extraArgs);
655
- 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);
656
658
  return args;
657
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
+ }
658
1615
  const dynamicImportModule = (specifier) => import(
659
1616
  /* @vite-ignore */
660
1617
  specifier
661
1618
  );
662
1619
  /**
663
- * Step a `HeadlessStage` in Node.js or Bun and stream raw `RGBA8888` frames (`-f rawvideo -pix_fmt rgba`)
664
- * 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.
665
1623
  */
666
1624
  async function encodeVideoWithFfmpeg(stage, options) {
667
1625
  const [cp, fs, os, path] = await Promise.all([
@@ -674,30 +1632,46 @@ async function encodeVideoWithFfmpeg(stage, options) {
674
1632
  const durationMs = totalFrames / stage.fps * 1e3;
675
1633
  const cw = stage.canvas.width || stage.width;
676
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);
677
1648
  let tempWavPath = null;
678
1649
  let audioWavPath;
679
- if (typeof options.audio === "string") audioWavPath = options.audio;
680
- else if (options.audio) {
681
- const wavBytes = options.audio instanceof Uint8Array ? options.audio : options.audio.toWav(durationMs);
682
- tempWavPath = path.join(os.tmpdir(), `holt-stage-audio-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.wav`);
683
- fs.writeFileSync(tempWavPath, wavBytes);
684
- 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
+ }
685
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");
686
1660
  const ffArgs = buildFfmpegRawVideoArgs({
687
1661
  width: cw,
688
1662
  height: ch,
689
1663
  fps: stage.fps,
690
1664
  outputPath: options.outputPath,
1665
+ inputFormat: resolvedInputFormat,
691
1666
  audioWavPath,
692
- videoCodec: options.videoCodec,
1667
+ videoCodec: resolvedVideoCodec,
693
1668
  preset: options.preset,
694
1669
  crf: options.crf,
695
1670
  outputPixelFormat: options.outputPixelFormat,
696
- audioCodec: options.audioCodec,
1671
+ audioCodec: resolvedAudioCodec,
697
1672
  audioBitrate: options.audioBitrate,
698
1673
  extraArgs: options.extraArgs
699
1674
  });
700
- const ffmpegBin = options.ffmpegPath ?? "ffmpeg";
701
1675
  const ff = cp.spawn(ffmpegBin, ffArgs, { stdio: [
702
1676
  "pipe",
703
1677
  "ignore",
@@ -786,17 +1760,39 @@ async function encodeVideoWithFfmpeg(stage, options) {
786
1760
  ff.once("error", onProcErr);
787
1761
  ff.once("close", onProcClose);
788
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
+ };
789
1783
  const clock = await stage.recordFrames({
790
1784
  frames: totalFrames,
791
1785
  digestEvery: options.digestEvery,
792
1786
  digestOptions: options.digestOptions,
1787
+ reuseFrameBuffer: !options.onFrame,
793
1788
  onFrame: async (frame) => {
794
1789
  if (frame.digest) digests.push(frame.digest);
795
1790
  if (options.onFrame) await options.onFrame(frame);
796
1791
  if (spawnError) throw spawnError;
797
1792
  if (stdinError) throw stdinError;
798
1793
  if (closed) throw new Error(`encodeVideoWithFfmpeg: ffmpeg exited early with code ${String(closedCode)}:\n${stderrLog}`);
799
- if (!ff.stdin.write(frame.rgba)) await waitDrainOrExit();
1794
+ const payload = encodeFramePayload(frame.rgba);
1795
+ if (!ff.stdin.write(payload)) await waitDrainOrExit();
800
1796
  }
801
1797
  });
802
1798
  ff.stdin.end();
@@ -811,7 +1807,9 @@ async function encodeVideoWithFfmpeg(stage, options) {
811
1807
  fps: stage.fps,
812
1808
  durationMs,
813
1809
  clock,
814
- digests
1810
+ digests,
1811
+ inputFormat: resolvedInputFormat,
1812
+ videoCodec: resolvedVideoCodec
815
1813
  };
816
1814
  } finally {
817
1815
  try {
@@ -822,4 +1820,155 @@ async function encodeVideoWithFfmpeg(stage, options) {
822
1820
  } catch {}
823
1821
  }
824
1822
  }
825
- export { buildFfmpegRawVideoArgs, createAudioTimeline, createHeadlessStage, createHeadlessStageAsync, encodeVideoWithFfmpeg, openDawnWebGpu, openHeadlessStage, openWgpuNativeFfi, renderStoryboard, requestHeadlessWebGpu };
1823
+ function summarizeValues(values) {
1824
+ if (values.length === 0) return {
1825
+ min: 0,
1826
+ max: 0,
1827
+ mean: 0,
1828
+ p50: 0,
1829
+ p95: 0,
1830
+ sum: 0
1831
+ };
1832
+ const sorted = [...values].sort((a, b) => a - b);
1833
+ let sum = 0;
1834
+ for (let i = 0; i < sorted.length; i++) sum += sorted[i];
1835
+ const n = sorted.length;
1836
+ const p50Idx = Math.min(n - 1, Math.floor((n - 1) * .5));
1837
+ const p95Idx = Math.min(n - 1, Math.ceil((n - 1) * .95));
1838
+ return {
1839
+ min: sorted[0],
1840
+ max: sorted[n - 1],
1841
+ mean: sum / n,
1842
+ p50: sorted[p50Idx],
1843
+ p95: sorted[p95Idx],
1844
+ sum
1845
+ };
1846
+ }
1847
+ const noop2dCtx = {
1848
+ canvas: {
1849
+ width: 1,
1850
+ height: 1
1851
+ },
1852
+ save() {},
1853
+ restore() {},
1854
+ scale() {},
1855
+ rotate() {},
1856
+ translate() {},
1857
+ transform() {},
1858
+ setTransform() {},
1859
+ resetTransform() {},
1860
+ clearRect() {},
1861
+ fillRect() {},
1862
+ strokeRect() {},
1863
+ beginPath() {},
1864
+ closePath() {},
1865
+ moveTo() {},
1866
+ lineTo() {},
1867
+ arc() {},
1868
+ arcTo() {},
1869
+ ellipse() {},
1870
+ rect() {},
1871
+ quadraticCurveTo() {},
1872
+ bezierCurveTo() {},
1873
+ fill() {},
1874
+ stroke() {},
1875
+ clip() {},
1876
+ drawImage() {},
1877
+ fillText() {},
1878
+ strokeText() {},
1879
+ measureText: (t) => ({ width: String(t).length * 8 }),
1880
+ createLinearGradient: () => ({ addColorStop() {} }),
1881
+ createRadialGradient: () => ({ addColorStop() {} }),
1882
+ createImageData: (w, h) => ({
1883
+ width: w,
1884
+ height: h,
1885
+ data: new Uint8ClampedArray(w * h * 4)
1886
+ }),
1887
+ getImageData: (_x, _y, w, h) => ({
1888
+ width: w,
1889
+ height: h,
1890
+ data: new Uint8ClampedArray(w * h * 4)
1891
+ }),
1892
+ putImageData() {}
1893
+ };
1894
+ function createZeroRasterCanvas(width, height) {
1895
+ return {
1896
+ width,
1897
+ height,
1898
+ getContext() {
1899
+ return noop2dCtx;
1900
+ }
1901
+ };
1902
+ }
1903
+ /**
1904
+ * Execute `N` deterministic zero-rasterization headless game rollouts in a single Node.js, Bun, or Deno process
1905
+ * (`stepSimOnly` / `fastForward` with a zero-overhead stub canvas — zero pixel rasterization or GPU driver required!),
1906
+ * returning per-run results and aggregated `min / max / mean / p50 / p95 / sum` balance statistics.
1907
+ */
1908
+ function runHeadlessRollouts(options) {
1909
+ const seeds = options.seeds;
1910
+ const runCount = Math.max(1, Math.floor(options.runs ?? seeds?.length ?? 16));
1911
+ const baseSeed = options.baseSeed ?? 1;
1912
+ const ticksPerRun = Math.max(1, Math.floor(options.ticksPerRun ?? 1800));
1913
+ const fps = Math.max(1, Math.min(240, options.fps ?? 60));
1914
+ const width = Math.max(1, Math.round(options.width ?? 1280));
1915
+ const height = Math.max(1, Math.round(options.height ?? 720));
1916
+ const t0 = performance.now();
1917
+ const results = [];
1918
+ const metricBuckets = /* @__PURE__ */ new Map();
1919
+ let totalTicks = 0;
1920
+ for (let r = 0; r < runCount; r++) {
1921
+ const seed = seeds && r < seeds.length ? seeds[r] : baseSeed + r;
1922
+ const stage = createHeadlessStage({
1923
+ createCanvas: createZeroRasterCanvas,
1924
+ width,
1925
+ height,
1926
+ fps,
1927
+ scene: options.createScene(r, seed)
1928
+ });
1929
+ let executedTicks = 0;
1930
+ try {
1931
+ if (options.onTick) for (let t = 0; t < ticksPerRun; t++) {
1932
+ if (options.onTick(stage, t, r, seed) === false) break;
1933
+ stage.fastForward(1);
1934
+ executedTicks++;
1935
+ }
1936
+ else {
1937
+ stage.fastForward(ticksPerRun);
1938
+ executedTicks = ticksPerRun;
1939
+ }
1940
+ totalTicks += executedTicks;
1941
+ const snap = stage.game.clock.snapshot();
1942
+ const metrics = options.extractMetrics(stage.scene, snap, r, seed);
1943
+ for (const key of Object.keys(metrics)) {
1944
+ let arr = metricBuckets.get(key);
1945
+ if (!arr) {
1946
+ arr = [];
1947
+ metricBuckets.set(key, arr);
1948
+ }
1949
+ arr.push(Number(metrics[key]) || 0);
1950
+ }
1951
+ results.push({
1952
+ runIndex: r,
1953
+ seed,
1954
+ ticks: executedTicks,
1955
+ simTimeMs: snap.simTimeMs,
1956
+ metrics
1957
+ });
1958
+ } finally {
1959
+ stage.destroy();
1960
+ }
1961
+ }
1962
+ const elapsedMs = Math.max(.001, performance.now() - t0);
1963
+ const summaryObj = {};
1964
+ for (const [key, vals] of metricBuckets.entries()) summaryObj[key] = summarizeValues(vals);
1965
+ return {
1966
+ runsCompleted: results.length,
1967
+ totalTicks,
1968
+ elapsedMs,
1969
+ ticksPerSecond: Math.round(totalTicks / elapsedMs * 1e3),
1970
+ summary: summaryObj,
1971
+ results
1972
+ };
1973
+ }
1974
+ export { buildFfmpegRawVideoArgs, createAudioTimeline, createHeadlessStage, createHeadlessStageAsync, encodeVideoWithFfmpeg, openDawnWebGpu, openHeadlessStage, openWgpuNativeFfi, renderStoryboard, requestHeadlessWebGpu, runHeadlessRollouts };