@zaisma/game-server 1.49.0 → 1.50.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.
@@ -197,7 +197,7 @@ function devScript() {
197
197
  closeMenus();
198
198
  return showPanel(true);
199
199
  }
200
- if (target?.closest(".bm-item")) return setTimeout(closeMenus, 0);
200
+ if (target?.closest(".bm-item") && !target.closest("[data-bench-clip]")) return setTimeout(closeMenus, 0);
201
201
  if (!target?.closest(".bench-menu")) closeMenus();
202
202
  });
203
203
  addEventListener("keydown", (event) => {
@@ -208,6 +208,62 @@ function devScript() {
208
208
  return;
209
209
  }
210
210
 
211
+ // --- Record a clip: the game's frame records it (local-play-clip.js), the bench checks and keeps it, and it plays back here before it's sent ---
212
+ const clipBody = document.getElementById("bench-clip-body");
213
+ let clipRequestId = null;
214
+ let lastAskedClipRequestId = null;
215
+ const escaped = (text) => String(text).replace(/[&<>"']/g, (character) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]);
216
+ const showClip = (markup) => {
217
+ clipBody.hidden = false;
218
+ clipBody.innerHTML = markup;
219
+ };
220
+ const base64Of = (buffer) => {
221
+ const bytes = new Uint8Array(buffer);
222
+ let text = "";
223
+ for (let i = 0; i < bytes.length; i += 32768) text += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
224
+ return btoa(text);
225
+ };
226
+ const keepClip = (body) =>
227
+ fetch(`/bench/clips?player=${playerNumber}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
228
+ .then((response) => response.json())
229
+ .then((answer) => {
230
+ if (answer.error) return showClip(`<span class="bp-error">${escaped(answer.error.message)}</span><span class="bp-note">${escaped(answer.error.fix)}</span>`);
231
+ const name = answer.clip_url.split("/").pop();
232
+ showClip(
233
+ `<video src="${escaped(answer.clip_url)}" muted loop autoplay playsinline style="width:100%;border-radius:6px"></video>` +
234
+ `<span class="bp-note">${(answer.duration_ms / 1000).toFixed(1)} s, ${answer.width_px} by ${answer.height_px}, ${Math.round(answer.size_bytes / 1024)} KB, <span title="${escaped(answer.clip_file)}">${escaped(name)}</span> in the bench's clips folder</span>` +
235
+ (answer.can_send ? `<button class="bm-item" type="button" data-bench-clip-send="${escaped(name)}"><span>Send to Zaisma</span></button>` : `<span class="bp-note">Send it with: <code>${escaped(answer.send_command)}</code></span>`),
236
+ );
237
+ })
238
+ .catch(() => showClip('<span class="bp-error">The bench didn\'t answer.</span>'));
239
+ const recordClip = (durationSec, requestId) => {
240
+ const game = frame.contentDocument?.getElementById("game");
241
+ clipRequestId = requestId || `clip_request_${Date.now()}`;
242
+ if (!game?.contentWindow || !game.getAttribute("src")) return keepClip({ request_id: clipRequestId, error_code: "game_not_playing", message: "The game isn't playing yet." });
243
+ showClip(`<span class="bp-note">Recording ${durationSec} seconds…</span>`);
244
+ game.contentWindow.postMessage({ kind: "zaisma-bench-record", requestId: clipRequestId, durationSec }, new URL(game.getAttribute("src"), frame.contentWindow.location.href).origin);
245
+ };
246
+ addEventListener("message", (event) => {
247
+ const game = frame.contentDocument?.getElementById("game");
248
+ if (!event.data || event.data.kind !== "zaisma-bench-clip" || event.data.requestId !== clipRequestId || event.source !== game?.contentWindow) return;
249
+ const given = event.data;
250
+ clipRequestId = null;
251
+ showClip('<span class="bp-note">Checking it…</span>');
252
+ keepClip(given.errorCode ? { request_id: given.requestId, error_code: given.errorCode, message: given.message } : { request_id: given.requestId, clip_base64: base64Of(given.clip), still_base64: base64Of(given.still) });
253
+ });
254
+ document.addEventListener("click", (event) => {
255
+ const target = event.target instanceof Element ? event.target : null;
256
+ const recorder = target?.closest("[data-bench-clip]");
257
+ if (recorder) return recordClip(Number(recorder.dataset.benchClip), null);
258
+ const sender = target?.closest("[data-bench-clip-send]");
259
+ if (!sender) return;
260
+ sender.disabled = true;
261
+ fetch("/bench/clips/send", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ clip_file: sender.dataset.benchClipSend }) })
262
+ .then((response) => response.json())
263
+ .then((answer) => sender.replaceWith(Object.assign(document.createElement("span"), { className: answer.error ? "bp-error" : "bp-note", textContent: answer.error ? `${answer.error.message} ${answer.error.fix ?? ""}` : answer.review_message })))
264
+ .catch(() => (sender.disabled = false));
265
+ });
266
+
211
267
  // About once a second: the player is still here, a game file changed (reload the game), and the room they're in (Add a player joins it).
212
268
  const check = () =>
213
269
  fetch(`/bench/state?player=${playerNumber}`)
@@ -215,6 +271,11 @@ function devScript() {
215
271
  .then((answer) => {
216
272
  if (reloadNumber !== null && answer.reloadNumber !== reloadNumber) frame.contentWindow?.location.reload();
217
273
  reloadNumber = answer.reloadNumber;
274
+ // The developer's AI asked for a clip (POST /bench/api/clips): this tab records it.
275
+ if (answer.clipRequest && answer.clipRequest.requestId !== lastAskedClipRequestId) {
276
+ lastAskedClipRequestId = answer.clipRequest.requestId;
277
+ recordClip(answer.clipRequest.durationSec, answer.clipRequest.requestId);
278
+ }
218
279
  if (answer.roomCode !== roomCode) {
219
280
  roomCode = answer.roomCode;
220
281
  // A new tab is a new player (a link to a new tab starts with nothing of this one's), into this room.
@@ -42,6 +42,7 @@ export const LOCAL_VERSION_ID: string;
42
42
  export const LOCAL_FOLDER: string;
43
43
  export const SERVED_ZAISMA_PATHS: string[];
44
44
  export const ONLY_ON_ZAISMA_PATHS: string[];
45
+ export const ONLY_ON_BENCH_PATHS: string[];
45
46
  export function startLocalPlay(options: LocalPlayOptions): Promise<LocalPlay>;
46
47
  export function benchFolderOf(gameFolder: string): string;
47
48
  export function serverEntryOf(gameFolder: string): string | null;
package/bin/local-play.js CHANGED
@@ -24,9 +24,10 @@ import { networkInterfaces } from "node:os";
24
24
  import { basename, extname, isAbsolute, join, relative as relativePath, resolve, sep } from "node:path";
25
25
  import { fileURLToPath } from "node:url";
26
26
  import { WebSocket, WebSocketServer } from "ws";
27
- import { BUSY_CLOSE_CODE, GameServerError, PASS_VERSION_NUMBER, RECEIPT_TOKEN_TYPE, RECEIPT_VERSION_NUMBER, generateSigningKey, guestName, jwks, loadSigningKey, roomCode, signPass, verifyPass } from "../src/internal.js";
27
+ import { BUSY_CLOSE_CODE, CLIP_LIMITS, checkClip, GameServerError, PASS_VERSION_NUMBER, RECEIPT_TOKEN_TYPE, RECEIPT_VERSION_NUMBER, generateSigningKey, guestName, jwks, loadSigningKey, roomCode, signPass, verifyPass } from "../src/internal.js";
28
28
  import { qrCodeModules, qrCodeSvg } from "../src/qr-code.js";
29
29
  import { ARRIVE_SCRIPT_SOURCE, FRAME_ALLOW, KEPT_SCRIPT_SOURCE, devScriptSource } from "./local-play-bench.js";
30
+ import { CLIP_RECORDING, clipScriptSource } from "./local-play-clip.js";
30
31
  import { isCertificateGood, makeCertificate } from "./local-play-certificate.js";
31
32
  import { COPY_STARTED_AGAIN_EXIT_CODE } from "./like-zaisma.js";
32
33
 
@@ -38,6 +39,8 @@ export const LOCAL_VERSION_ID = "version_local";
38
39
  export const LOCAL_FOLDER = ".zaisma-local";
39
40
  /** Every _zaisma/ file the games Worker serves, split by whether it works here or only loads and does nothing (test/node/local-play-parity.test.ts holds this to apps/games/src/index.ts). */
40
41
  export const SERVED_ZAISMA_PATHS = ["_zaisma/v1.js", "_zaisma/v1.d.ts", "_zaisma/relay.js", "_zaisma/picture.js", "_zaisma/saves.js", "_zaisma/restore"];
42
+ /** The _zaisma/ files only the bench serves, which Zaisma's games Worker never does: the bench's clip recorder. */
43
+ export const ONLY_ON_BENCH_PATHS = ["_zaisma/clip.js"];
41
44
  export const ONLY_ON_ZAISMA_PATHS = ["_zaisma/performance.js", "_zaisma/pressure.js", "_zaisma/warm", "_zaisma/warm.json", "_zaisma/warm-redirects.json", "_zaisma/warm.js"];
42
45
  const OPTION_NAMES = ["gameFolder", "port", "isOnNetwork", "gameSlug", "benchFolder", "zaismaKey", "developerApiUrl", "log"];
43
46
  const SAVE_LIMIT_BYTES = 5 * 1024 * 1024;
@@ -424,6 +427,65 @@ export async function startLocalPlay(givenOptions) {
424
427
  const PLAYER_OPEN_MS = 70_000;
425
428
  const PLAYER_PATH = /^\/p\/([1-9][0-9]{0,3})(?=\/|$)/;
426
429
  const heardAtMs = new Map(); // player number -> when its dev page last asked
430
+ const clipRequests = new Map(); // player number -> the AI's recording it waits for: { requestId, durationSec, settle }
431
+ /**
432
+ * Whether a request comes from the bench's own page on this computer: its Origin is the bench's (a game's page, or another site, has its
433
+ * own), and it comes from this computer, so a device on the same Wi-Fi (on-network) can't write recordings or send one with the key.
434
+ */
435
+ const isBenchPage = (request) => request.headers.origin === originFor(request, ports.bench) && ["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(request.socket.remoteAddress ?? "");
436
+ /** A recorded clip's body: JSON up to the clip's most in base64, with room. */
437
+ const readClipBody = async (request) => {
438
+ const chunks = [];
439
+ let sizeBytes = 0;
440
+ for await (const chunk of request) {
441
+ sizeBytes += chunk.length;
442
+ if (sizeBytes > CLIP_LIMITS.maximumBodySizeBytes) return {};
443
+ chunks.push(chunk);
444
+ }
445
+ try {
446
+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
447
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
448
+ } catch {
449
+ return {};
450
+ }
451
+ };
452
+ /** Keeps a recording in the bench's folder once it passes Zaisma's checks for a clip; an error answer otherwise, with its fix. */
453
+ const keepClip = async (given) => {
454
+ const fixFor = {
455
+ no_canvas: "This game draws no canvas to record: record any MP4 of it (a screen recorder) and send it with zaisma clip <file.mp4> --game <slug>.",
456
+ recording_unsupported: "This browser has no H.264 encoder: open the bench in Chrome, Edge or Safari, or record any MP4 and send it with zaisma clip.",
457
+ canvas_not_readable: "Serve the pictures the game draws from its own folder (or with CORS), or record any MP4 and send it with zaisma clip.",
458
+ already_recording: "Wait for the recording to finish.",
459
+ game_not_playing: "Press Play on the bench's game page first: the game loads when Play is pressed.",
460
+ recording_failed: "Try again with the game playing in front; or record any MP4 and send it with zaisma clip.",
461
+ };
462
+ if (typeof given.error_code === "string") {
463
+ const code = Object.hasOwn(fixFor, given.error_code) ? given.error_code : "recording_failed";
464
+ return { error: { code, message: typeof given.message === "string" ? given.message.slice(0, 300) : "The recording failed.", fix: fixFor[code] } };
465
+ }
466
+ const clipBytes = typeof given.clip_base64 === "string" ? Buffer.from(given.clip_base64, "base64") : Buffer.alloc(0);
467
+ const stillBytes = typeof given.still_base64 === "string" ? Buffer.from(given.still_base64, "base64") : Buffer.alloc(0);
468
+ const checked = checkClip(new Uint8Array(clipBytes));
469
+ if ("problem" in checked) return { error: checked.problem };
470
+ if (stillBytes.length < 3 || stillBytes[0] !== 0xff || stillBytes[1] !== 0xd8 || stillBytes.length > CLIP_LIMITS.maximumStillSizeBytes) return { error: { code: "bad_clip_still", message: "The recording's still isn't a JPEG.", fix: "Record the clip again." } };
471
+ const name = `clip-${new Date(now()).toISOString().replace(/[:.]/g, "-")}`;
472
+ mkdirSync(join(localFolder, "clips"), { recursive: true });
473
+ writeFileSync(join(localFolder, "clips", `${name}.mp4`), clipBytes);
474
+ writeFileSync(join(localFolder, "clips", `${name}.jpg`), stillBytes);
475
+ const clipFile = join(localFolder, "clips", `${name}.mp4`), stillFile = join(localFolder, "clips", `${name}.jpg`);
476
+ log(`Recorded a ${(checked.facts.durationMs / 1000).toFixed(1)} s clip: ${clipFile}. Send it with: npx @zaisma/cli clip ${clipFile} --game ${gameSlug ?? "<slug>"}`);
477
+ return {
478
+ clip_file: clipFile,
479
+ still_file: stillFile,
480
+ clip_url: `${localhostOrigin(ports.bench)}/bench/clip-files/${name}.mp4`,
481
+ width_px: checked.facts.widthPx,
482
+ height_px: checked.facts.heightPx,
483
+ duration_ms: checked.facts.durationMs,
484
+ size_bytes: clipBytes.length,
485
+ can_send: Boolean(zaismaKey && gameSlug),
486
+ send_command: `npx @zaisma/cli clip ${clipFile} --game ${gameSlug ?? "<slug>"}`,
487
+ };
488
+ };
427
489
  const lastRoomCodes = new Map(); // player number -> the room it was last seen in, to go back to after a sign-in that left the page
428
490
  let reloadNumber = 0;
429
491
  /** Tell every dev page to reload its game, at its next ask. */
@@ -633,6 +695,19 @@ export async function startLocalPlay(givenOptions) {
633
695
  const room = typeof body.room_code === "string" && /^[A-Z0-9]{6}$/.test(body.room_code) ? body.room_code : null;
634
696
  return reply(201, { ...apiOpenPlayer(playerNumber), url: `${localhostOrigin(ports.bench)}/?player=${playerNumber}${room ? `&room=${room}` : ""}` });
635
697
  }
698
+ // A clip of the game as it plays now, for the developer's AI: the open tab records it (the one given, else the one last heard from).
699
+ if (path === "/bench/api/clips" && method === "POST") {
700
+ const open = openPlayerNumbers();
701
+ const playerNumber = Number.isInteger(body.player_number) ? body.player_number : [...open].sort((first, second) => (heardAtMs.get(second) ?? 0) - (heardAtMs.get(first) ?? 0))[0];
702
+ if (!playerNumber || !open.includes(playerNumber)) return fail(409, "no_open_player", "No open tab of the bench to record the game in.", "Open the bench in a browser (POST /bench/api/open-players gives a url), press Play, then ask again.");
703
+ const durationSec = Number.isFinite(body.duration_sec) ? Math.min(CLIP_RECORDING.maximumDurationSec, Math.max(CLIP_RECORDING.minimumDurationSec, body.duration_sec)) : CLIP_RECORDING.maximumDurationSec;
704
+ clipRequests.get(playerNumber)?.settle({ error: { code: "recording_replaced", message: "Another recording was asked for.", fix: "Ask once at a time." } });
705
+ const answer = await new Promise((settle) => {
706
+ const timer = setTimeout(() => settle({ error: { code: "recording_timed_out", message: "The tab didn't record a clip in time.", fix: "Keep the bench's tab in front with the game playing (a hidden tab doesn't draw), then ask again." } }), (durationSec + 60) * 1000);
707
+ clipRequests.set(playerNumber, { requestId: `clip_request_${randomText(10)}`, durationSec, settle: (given) => { clearTimeout(timer); clipRequests.delete(playerNumber); settle(given); } });
708
+ });
709
+ return answer.error ? fail(400, answer.error.code, answer.error.message, answer.error.fix) : reply(201, answer);
710
+ }
636
711
  const openMatch = /^\/bench\/api\/open-players\/([1-9][0-9]{0,3})(\/pass)?$/.exec(path);
637
712
  if (openMatch) {
638
713
  const playerNumber = Number(openMatch[1]);
@@ -1114,7 +1189,8 @@ export async function startLocalPlay(givenOptions) {
1114
1189
  if (playerNumber) heardAtMs.set(playerNumber, now());
1115
1190
  const roomCode = playerNumber ? roomOfPlayerId(playerIdOf(playerNumber)) : null;
1116
1191
  if (roomCode) lastRoomCodes.set(playerNumber, roomCode);
1117
- return reply(200, { reloadNumber, roomCode, openPlayerNumbers: openPlayerNumbers() });
1192
+ const clipRequest = clipRequests.get(playerNumber);
1193
+ return reply(200, { reloadNumber, roomCode, openPlayerNumbers: openPlayerNumbers(), clipRequest: clipRequest ? { requestId: clipRequest.requestId, durationSec: clipRequest.durationSec } : null });
1118
1194
  }
1119
1195
  if (path === "/bench/claim" && request.method === "POST") {
1120
1196
  const given = await readJson(request);
@@ -1124,6 +1200,39 @@ export async function startLocalPlay(givenOptions) {
1124
1200
  response.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store" });
1125
1201
  return response.end(ARRIVE_SCRIPT_SOURCE);
1126
1202
  }
1203
+ // A clip the bench's page recorded from the game (local-play-clip.js), or why it couldn't: checked as Zaisma checks one, then kept in the bench's folder.
1204
+ if (path === "/bench/clips" && request.method === "POST") {
1205
+ if (!isBenchPage(request)) return reply(403, { error: { code: "bad_origin", message: "Only the bench's own page records clips.", fix: "Press Record a clip on the bench's bar." } });
1206
+ const given = await readClipBody(request);
1207
+ const answer = await keepClip(given);
1208
+ const waiting = clipRequests.get(playerNumber);
1209
+ if (waiting && waiting.requestId === given.request_id) waiting.settle(answer);
1210
+ return reply(answer.error ? 400 : 201, answer);
1211
+ }
1212
+ const clipFileMatch = /^\/bench\/clip-files\/(clip-[0-9TZ-]+\.(mp4|jpg))$/.exec(path);
1213
+ if (clipFileMatch && request.method === "GET") {
1214
+ const file = join(localFolder, "clips", clipFileMatch[1]);
1215
+ if (!existsSync(file)) return reply(404, { error: { code: "no_clip_file", message: "The bench has no such clip.", fix: "Record one with Record a clip." } });
1216
+ response.writeHead(200, { "Content-Type": clipFileMatch[2] === "mp4" ? "video/mp4" : "image/jpeg", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
1217
+ return response.end(readFileSync(file));
1218
+ }
1219
+ // Send to Zaisma, from the bench's bar only: the clip and its still, with the bench's key, as zaisma clip sends them.
1220
+ if (path === "/bench/clips/send" && request.method === "POST") {
1221
+ if (!isBenchPage(request)) return reply(403, { error: { code: "bad_origin", message: "Only the bench's own page sends clips.", fix: "Press Send to Zaisma on the bench's bar." } });
1222
+ const given = await readJson(request);
1223
+ const name = typeof given.clip_file === "string" && /^clip-[0-9TZ-]+\.mp4$/.test(given.clip_file) ? given.clip_file : null;
1224
+ if (!name || !existsSync(join(localFolder, "clips", name))) return reply(404, { error: { code: "no_clip_file", message: "The bench has no such clip.", fix: "Record one with Record a clip." } });
1225
+ if (!zaismaKey || !gameSlug) return reply(400, { error: { code: "no_key", message: "The bench has no API key or game to send it with.", fix: `Run zaisma clip ${join(localFolder, "clips", name)} --game <slug> with ZAISMA_KEY set.` } });
1226
+ const sent = await fetch(`${developerApiUrl}/games/${gameSlug}/clip`, {
1227
+ method: "PUT",
1228
+ headers: { authorization: `Bearer ${zaismaKey}`, "content-type": "application/json", "x-zaisma-client": "bench" },
1229
+ body: JSON.stringify({ clip_base64: readFileSync(join(localFolder, "clips", name)).toString("base64"), still_base64: readFileSync(join(localFolder, "clips", name.replace(/\.mp4$/, ".jpg"))).toString("base64") }),
1230
+ }).catch(() => null);
1231
+ const answer = sent ? await sent.json().catch(() => null) : null;
1232
+ if (!sent || !answer) return reply(502, { error: { code: "server_unreachable", message: "Zaisma couldn't be reached.", fix: "Check the connection, then press Send to Zaisma again." } });
1233
+ log(sent.ok ? `Clip sent to Zaisma: ${answer.review_message}` : `Zaisma refused the clip: ${answer.error?.message ?? sent.status}`);
1234
+ return reply(sent.status, answer);
1235
+ }
1127
1236
  if (path === "/bench/leave" && request.method === "POST") {
1128
1237
  heardAtMs.delete(playerNumber);
1129
1238
  return reply(200, { isLeft: true });
@@ -1222,6 +1331,7 @@ export async function startLocalPlay(givenOptions) {
1222
1331
  return send(200, js, withSetup("__ZAISMA__", config, sdkText("zaisma.js")));
1223
1332
  }
1224
1333
  if (path === "_zaisma/v1.d.ts") return send(200, "text/plain; charset=utf-8", sdkText("zaisma.d.ts"));
1334
+ if (path === "_zaisma/clip.js") return send(200, js, clipScriptSource(benchOrigin));
1225
1335
  if (path === "_zaisma/relay.js") return send(200, js, withSetup("__ZAISMA_RELAY__", { rooms: originFor(request, ports.rooms), game: gameSlug, site: benchOrigin, ownRelayHosts: [], fetchEarly: false }, sdkText("relay.js")));
1226
1336
  if (path === "_zaisma/picture.js") return send(200, js, withSetup("__ZAISMA_PICTURE__", { site: benchOrigin }, sdkText("picture.js")));
1227
1337
  if (path === "_zaisma/saves.js") {
@@ -1248,7 +1358,7 @@ export async function startLocalPlay(givenOptions) {
1248
1358
  const contentType = TYPES[extname(target).toLowerCase()] ?? "application/octet-stream";
1249
1359
  const bytes = readFileSync(target);
1250
1360
  if (contentType.startsWith("text/html")) {
1251
- const injected = withScripts(bytes.toString("utf8"), [`/_zaisma/saves.js?v=${SCRIPTS_VERSION_NUMBER}&version_id=${LOCAL_VERSION_ID}`]);
1361
+ const injected = withScripts(bytes.toString("utf8"), [`/_zaisma/saves.js?v=${SCRIPTS_VERSION_NUMBER}&version_id=${LOCAL_VERSION_ID}`, `/_zaisma/clip.js?v=${SCRIPTS_VERSION_NUMBER}`]);
1252
1362
  return send(200, contentType, injected);
1253
1363
  }
1254
1364
  const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range ?? "");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/game-server",
3
- "version": "1.49.0",
3
+ "version": "1.50.0",
4
4
  "description": "Run your Zaisma game server: the same rooms on Zaisma or on your own server.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",
package/src/clips.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A game's clip, as files: the rules a clip keeps (up to 6 seconds, silent, H.264, fitting the 1200 by 630 share card) and the reader that
3
+ * checks them from an MP4's own boxes, with no decoder. Zaisma's developer API checks every clip with it, and play-locally's bench checks
4
+ * what it recorded before writing it, so both say the same.
5
+ */
6
+ /** A clip's limits: what iMessage, Discord and Telegram all play, fitted inside the 1200 by 630 share card. */
7
+ export declare const CLIP_LIMITS: {
8
+ readonly maximumDurationMs: 6000;
9
+ readonly maximumWidthPx: 1200;
10
+ readonly maximumHeightPx: 630;
11
+ /** The least a clip takes on its long and short sides, as a share picture. */
12
+ readonly minimumLongSidePx: 600;
13
+ readonly minimumShortSidePx: 315;
14
+ /** About 3 MB is usual: 6 seconds at 1200 by 630 and 4 megabits a second. */
15
+ readonly maximumSizeBytes: number;
16
+ readonly maximumStillSizeBytes: number;
17
+ /** The developer API's JSON body: the clip and its still in base64 (a third larger), with room for the field names. */
18
+ readonly maximumBodySizeBytes: number;
19
+ };
20
+ /** What a clip file is, read from its boxes. */
21
+ export interface Mp4Facts {
22
+ widthPx: number;
23
+ heightPx: number;
24
+ durationMs: number;
25
+ /** The video track's sample format, like avc1 (H.264) or hvc1 (HEVC). */
26
+ videoFormat: string;
27
+ videoTrackCount: number;
28
+ soundTrackCount: number;
29
+ /** Fragmented MP4s (as a browser's recorder writes) keep their length in fragments, not in the index. */
30
+ isFragmented: boolean;
31
+ }
32
+ /** Why a file isn't a clip, in the developer API's error codes. */
33
+ export type ClipProblemCode = "not_a_clip" | "clip_has_sound" | "clip_too_long" | "bad_clip_dimensions" | "clip_too_big";
34
+ export interface ClipProblem {
35
+ code: ClipProblemCode;
36
+ message: string;
37
+ fix: string;
38
+ }
39
+ /** An MP4's facts from its boxes, or null when it isn't an MP4 this can read. */
40
+ export declare function readMp4(bytes: Uint8Array): Mp4Facts | null;
41
+ /** Whether a clip's size fits the share card: inside 1200 by 630, and at least 600 by 315 on its long and short sides. */
42
+ export declare function isClipSizeFitting(widthPx: number, heightPx: number): boolean;
43
+ /** The one ffmpeg line that makes any video into a clip, for fixes: its first 6 seconds, fitted inside the card, silent, H.264. */
44
+ export declare const CLIP_FFMPEG_LINE = "ffmpeg -i in.mp4 -t 6 -an -vf \"scale=1200:630:force_original_aspect_ratio=decrease:force_divisible_by=2\" -c:v libx264 -pix_fmt yuv420p -movflags +faststart clip.mp4";
45
+ /** A clip file's facts, or the first rule it breaks. */
46
+ export declare function checkClip(bytes: Uint8Array): {
47
+ facts: Mp4Facts;
48
+ } | {
49
+ problem: ClipProblem;
50
+ };
package/src/clips.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * A game's clip, as files: the rules a clip keeps (up to 6 seconds, silent, H.264, fitting the 1200 by 630 share card) and the reader that
3
+ * checks them from an MP4's own boxes, with no decoder. Zaisma's developer API checks every clip with it, and play-locally's bench checks
4
+ * what it recorded before writing it, so both say the same.
5
+ */
6
+ /** A clip's limits: what iMessage, Discord and Telegram all play, fitted inside the 1200 by 630 share card. */
7
+ export const CLIP_LIMITS = {
8
+ maximumDurationMs: 6000,
9
+ maximumWidthPx: 1200,
10
+ maximumHeightPx: 630,
11
+ /** The least a clip takes on its long and short sides, as a share picture. */
12
+ minimumLongSidePx: 600,
13
+ minimumShortSidePx: 315,
14
+ /** About 3 MB is usual: 6 seconds at 1200 by 630 and 4 megabits a second. */
15
+ maximumSizeBytes: 6 * 1024 * 1024,
16
+ maximumStillSizeBytes: 2 * 1024 * 1024,
17
+ /** The developer API's JSON body: the clip and its still in base64 (a third larger), with room for the field names. */
18
+ maximumBodySizeBytes: 11 * 1024 * 1024,
19
+ };
20
+ /** The sample formats that are H.264. */
21
+ const H264_FORMATS = ["avc1", "avc3"];
22
+ /** How deep boxes may nest inside a track: a clip's go about four deep. */
23
+ const MAXIMUM_BOX_DEPTH_COUNT = 12;
24
+ const CONTAINER_BOXES = new Set(["moov", "trak", "mdia", "minf", "stbl", "edts", "mvex"]);
25
+ /** The boxes between two places in the file, in order; null when one runs past its parent or is too short to be a box. */
26
+ function boxesIn(bytes, startIndex, endIndex) {
27
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
28
+ const boxes = [];
29
+ let atIndex = startIndex;
30
+ while (atIndex + 8 <= endIndex) {
31
+ let sizeBytes = view.getUint32(atIndex);
32
+ const type = String.fromCharCode(bytes[atIndex + 4], bytes[atIndex + 5], bytes[atIndex + 6], bytes[atIndex + 7]);
33
+ let headerBytes = 8;
34
+ if (sizeBytes === 1) {
35
+ if (atIndex + 16 > endIndex)
36
+ return null;
37
+ const highNumber = view.getUint32(atIndex + 8), lowNumber = view.getUint32(atIndex + 12);
38
+ sizeBytes = highNumber * 2 ** 32 + lowNumber;
39
+ headerBytes = 16;
40
+ }
41
+ else if (sizeBytes === 0) {
42
+ sizeBytes = endIndex - atIndex;
43
+ }
44
+ if (sizeBytes < headerBytes || atIndex + sizeBytes > endIndex)
45
+ return null;
46
+ boxes.push({ type, bodyStartIndex: atIndex + headerBytes, endIndex: atIndex + sizeBytes });
47
+ atIndex += sizeBytes;
48
+ }
49
+ return boxes;
50
+ }
51
+ /** A track's facts from its boxes, or null when its boxes are broken. */
52
+ function trackFacts(bytes, trak) {
53
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
54
+ let handler = "", format = "", widthPx = 0, heightPx = 0, durationMs = null;
55
+ // A real clip nests a handful of boxes deep; a file nesting deeper is broken (and can't run the reader out of stack).
56
+ const visit = (box, depthNumber) => {
57
+ if (CONTAINER_BOXES.has(box.type)) {
58
+ if (depthNumber >= MAXIMUM_BOX_DEPTH_COUNT)
59
+ return false;
60
+ const children = boxesIn(bytes, box.bodyStartIndex, box.endIndex);
61
+ return children !== null && children.every((child) => visit(child, depthNumber + 1));
62
+ }
63
+ const bodyIndex = box.bodyStartIndex, bodyBytes = box.endIndex - box.bodyStartIndex;
64
+ if (box.type === "tkhd") {
65
+ // Width and height are the last 8 bytes, 16.16 fixed point, whatever the version.
66
+ if (bodyBytes < 84)
67
+ return false;
68
+ widthPx = Math.round(view.getUint32(box.endIndex - 8) / 65536);
69
+ heightPx = Math.round(view.getUint32(box.endIndex - 4) / 65536);
70
+ }
71
+ else if (box.type === "mdhd") {
72
+ const boxVersionNumber = bytes[bodyIndex];
73
+ if (bodyBytes < (boxVersionNumber === 1 ? 32 : 20))
74
+ return false;
75
+ const timescaleNumber = view.getUint32(bodyIndex + (boxVersionNumber === 1 ? 20 : 12));
76
+ const durationNumber = boxVersionNumber === 1 ? view.getUint32(bodyIndex + 24) * 2 ** 32 + view.getUint32(bodyIndex + 28) : view.getUint32(bodyIndex + 16);
77
+ if (timescaleNumber > 0)
78
+ durationMs = Math.round((durationNumber / timescaleNumber) * 1000);
79
+ }
80
+ else if (box.type === "hdlr") {
81
+ if (bodyBytes < 12)
82
+ return false;
83
+ handler = String.fromCharCode(...bytes.subarray(bodyIndex + 8, bodyIndex + 12));
84
+ }
85
+ else if (box.type === "stsd") {
86
+ // Version and flags, the entry count, then the first entry: its size and its format.
87
+ if (bodyBytes < 16)
88
+ return false;
89
+ format = String.fromCharCode(...bytes.subarray(bodyIndex + 12, bodyIndex + 16));
90
+ }
91
+ return true;
92
+ };
93
+ const children = boxesIn(bytes, trak.bodyStartIndex, trak.endIndex);
94
+ if (!children || !children.every((child) => visit(child, 1)))
95
+ return null;
96
+ return { handler, format, widthPx, heightPx, durationMs };
97
+ }
98
+ /** An MP4's facts from its boxes, or null when it isn't an MP4 this can read. */
99
+ export function readMp4(bytes) {
100
+ const top = boxesIn(bytes, 0, bytes.byteLength);
101
+ if (!top || top[0]?.type !== "ftyp")
102
+ return null;
103
+ const brand = String.fromCharCode(...bytes.subarray(top[0].bodyStartIndex, top[0].bodyStartIndex + 4));
104
+ if (brand === "qt " || /^M4[ABP] /.test(brand))
105
+ return null;
106
+ const moov = top.find((box) => box.type === "moov");
107
+ if (!moov)
108
+ return null;
109
+ const moovChildren = boxesIn(bytes, moov.bodyStartIndex, moov.endIndex);
110
+ if (!moovChildren)
111
+ return null;
112
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
113
+ let movieDurationMs = null;
114
+ const mvhd = moovChildren.find((box) => box.type === "mvhd");
115
+ if (mvhd) {
116
+ const boxVersionNumber = bytes[mvhd.bodyStartIndex];
117
+ if (mvhd.endIndex - mvhd.bodyStartIndex >= (boxVersionNumber === 1 ? 32 : 20)) {
118
+ const timescaleNumber = view.getUint32(mvhd.bodyStartIndex + (boxVersionNumber === 1 ? 20 : 12));
119
+ const durationNumber = boxVersionNumber === 1 ? view.getUint32(mvhd.bodyStartIndex + 24) * 2 ** 32 + view.getUint32(mvhd.bodyStartIndex + 28) : view.getUint32(mvhd.bodyStartIndex + 16);
120
+ if (timescaleNumber > 0)
121
+ movieDurationMs = Math.round((durationNumber / timescaleNumber) * 1000);
122
+ }
123
+ }
124
+ const tracks = [];
125
+ for (const trak of moovChildren.filter((box) => box.type === "trak")) {
126
+ const facts = trackFacts(bytes, trak);
127
+ if (!facts)
128
+ return null;
129
+ tracks.push(facts);
130
+ }
131
+ const videoTracks = tracks.filter((track) => track.handler === "vide");
132
+ const video = videoTracks[0];
133
+ if (!video)
134
+ return null;
135
+ const isFragmented = moovChildren.some((box) => box.type === "mvex") || top.some((box) => box.type === "moof");
136
+ return {
137
+ widthPx: video.widthPx,
138
+ heightPx: video.heightPx,
139
+ durationMs: Math.max(video.durationMs ?? 0, movieDurationMs ?? 0),
140
+ videoFormat: video.format,
141
+ videoTrackCount: videoTracks.length,
142
+ soundTrackCount: tracks.filter((track) => track.handler === "soun").length,
143
+ isFragmented,
144
+ };
145
+ }
146
+ /** Whether a clip's size fits the share card: inside 1200 by 630, and at least 600 by 315 on its long and short sides. */
147
+ export function isClipSizeFitting(widthPx, heightPx) {
148
+ return (widthPx <= CLIP_LIMITS.maximumWidthPx &&
149
+ heightPx <= CLIP_LIMITS.maximumHeightPx &&
150
+ Math.max(widthPx, heightPx) >= CLIP_LIMITS.minimumLongSidePx &&
151
+ Math.min(widthPx, heightPx) >= CLIP_LIMITS.minimumShortSidePx);
152
+ }
153
+ /** The one ffmpeg line that makes any video into a clip, for fixes: its first 6 seconds, fitted inside the card, silent, H.264. */
154
+ export const CLIP_FFMPEG_LINE = `ffmpeg -i in.mp4 -t 6 -an -vf "scale=1200:630:force_original_aspect_ratio=decrease:force_divisible_by=2" -c:v libx264 -pix_fmt yuv420p -movflags +faststart clip.mp4`;
155
+ /** A clip file's facts, or the first rule it breaks. */
156
+ export function checkClip(bytes) {
157
+ if (bytes.byteLength > CLIP_LIMITS.maximumSizeBytes) {
158
+ return { problem: { code: "clip_too_big", message: `The clip is ${(bytes.byteLength / 1048576).toFixed(1)} MB, over ${CLIP_LIMITS.maximumSizeBytes / 1048576} MB.`, fix: `Save it at a lower bitrate (about 4 megabits a second is plenty), like: ${CLIP_FFMPEG_LINE.replace("-pix_fmt", "-b:v 4M -pix_fmt")}` } };
159
+ }
160
+ const facts = readMp4(bytes);
161
+ if (!facts)
162
+ return { problem: { code: "not_a_clip", message: "That isn't an MP4 video with a picture track.", fix: `Send an MP4 (H.264), like the bench's Record a clip makes, or make one: ${CLIP_FFMPEG_LINE}` } };
163
+ if (facts.isFragmented)
164
+ return { problem: { code: "not_a_clip", message: "The MP4 is fragmented (as a browser's recorder saves it), so its length can't be read.", fix: `Save it as a plain MP4: ${CLIP_FFMPEG_LINE}` } };
165
+ if (facts.videoTrackCount > 1)
166
+ return { problem: { code: "not_a_clip", message: `The MP4 has ${facts.videoTrackCount} picture tracks.`, fix: `Send one picture track: ${CLIP_FFMPEG_LINE}` } };
167
+ if (!H264_FORMATS.includes(facts.videoFormat)) {
168
+ return { problem: { code: "not_a_clip", message: `The clip's video is ${JSON.stringify(facts.videoFormat)}, not H.264, which every app that plays a link's video plays.`, fix: `Save it as H.264: ${CLIP_FFMPEG_LINE}` } };
169
+ }
170
+ if (facts.soundTrackCount)
171
+ return { problem: { code: "clip_has_sound", message: "The clip has a sound track; a clip is silent.", fix: `Take the sound out (ffmpeg's -an): ${CLIP_FFMPEG_LINE}` } };
172
+ if (facts.durationMs > CLIP_LIMITS.maximumDurationMs) {
173
+ return { problem: { code: "clip_too_long", message: `The clip runs ${(facts.durationMs / 1000).toFixed(1)} seconds, over ${CLIP_LIMITS.maximumDurationMs / 1000}.`, fix: `Cut it to at most 6 seconds that loop well (ffmpeg's -t 6): ${CLIP_FFMPEG_LINE}` } };
174
+ }
175
+ if (facts.durationMs <= 0)
176
+ return { problem: { code: "not_a_clip", message: "The clip's length can't be read: it says 0 seconds.", fix: `Save it again: ${CLIP_FFMPEG_LINE}` } };
177
+ if (!isClipSizeFitting(facts.widthPx, facts.heightPx)) {
178
+ return {
179
+ problem: {
180
+ code: "bad_clip_dimensions",
181
+ message: `The clip is ${facts.widthPx} by ${facts.heightPx} px.`,
182
+ fix: `Fit it inside ${CLIP_LIMITS.maximumWidthPx} by ${CLIP_LIMITS.maximumHeightPx} px, at least ${CLIP_LIMITS.minimumLongSidePx} by ${CLIP_LIMITS.minimumShortSidePx}: ${CLIP_FFMPEG_LINE}`,
183
+ },
184
+ };
185
+ }
186
+ return { facts };
187
+ }
package/src/internal.d.ts CHANGED
@@ -15,3 +15,4 @@ export * from "./chat.ts";
15
15
  export * from "./voice-ticket.ts";
16
16
  export * from "./relay.ts";
17
17
  export * from "./doors.ts";
18
+ export { CLIP_FFMPEG_LINE, CLIP_LIMITS, checkClip, isClipSizeFitting, readMp4, type ClipProblem, type ClipProblemCode, type Mp4Facts } from "./clips.ts";
package/src/internal.js CHANGED
@@ -17,3 +17,4 @@ export * from "./chat.js";
17
17
  export * from "./voice-ticket.js";
18
18
  export * from "./relay.js";
19
19
  export * from "./doors.js";
20
+ export { CLIP_FFMPEG_LINE, CLIP_LIMITS, checkClip, isClipSizeFitting, readMp4 } from "./clips.js";