@zaisma/game-server 1.49.0 → 1.51.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/bench/brand/_headers +3 -1
- package/bench/brand/design/videos/share-card-moving.mp4 +0 -0
- package/bench/brand/share-card-letters.png +0 -0
- package/bench/brand/zaisma-wordmark-glass-black-448.png +0 -0
- package/bench/brand/zaisma-wordmark-glass-white-448.png +0 -0
- package/bench/glass.js +11305 -10431
- package/bin/local-play-bench.js +62 -1
- package/bin/local-play.d.ts +1 -0
- package/bin/local-play.js +132 -8
- package/package.json +1 -1
- package/sdk/sound.js +84 -0
- package/sdk/zaisma.d.ts +19 -3
- package/sdk/zaisma.js +23 -1
- package/src/clips.d.ts +50 -0
- package/src/clips.js +187 -0
- package/src/internal.d.ts +1 -0
- package/src/internal.js +1 -0
package/bin/local-play-bench.js
CHANGED
|
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[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.
|
package/bin/local-play.d.ts
CHANGED
|
@@ -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
|
|
|
@@ -37,7 +38,9 @@ export const LOCAL_VERSION_ID = "version_local";
|
|
|
37
38
|
/** The folder in the game's folder that held what the bench keeps, before it moved out (benchFolderOf): still never served, watched or uploaded, and moved out on the next start. */
|
|
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
|
-
export const SERVED_ZAISMA_PATHS = ["_zaisma/v1.js", "_zaisma/v1.d.ts", "_zaisma/relay.js", "_zaisma/picture.js", "_zaisma/saves.js", "_zaisma/restore"];
|
|
41
|
+
export const SERVED_ZAISMA_PATHS = ["_zaisma/v1.js", "_zaisma/v1.d.ts", "_zaisma/relay.js", "_zaisma/picture.js", "_zaisma/sound.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]);
|
|
@@ -978,10 +1053,23 @@ export async function startLocalPlay(givenOptions) {
|
|
|
978
1053
|
|
|
979
1054
|
// Friends: who's playing, the Friend marks in the players sheet, and blocks.
|
|
980
1055
|
if (request.method === "GET" && path === `${game}/friends`) return fragment(account ? glass.friendsHereHtml(gameSlug, friendsPlaying(account.id)) : "");
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
1056
|
+
// The guide's places, from the bench's own players (glass.guidePlaceHtml); its sound and invites are kept nowhere here.
|
|
1057
|
+
const guideMatch = /^\/guide\/([a-z]+)$/.exec(path);
|
|
1058
|
+
if (guideMatch && request.method === "GET") {
|
|
1059
|
+
const friendIds = new Set(account ? friendIdsOf(account.id) : []);
|
|
1060
|
+
const markup = glass.guidePlaceHtml(guideMatch[1], url.searchParams, {
|
|
1061
|
+
gameSlug,
|
|
1062
|
+
account: account ? { username: account.username, playerId: account.playerId } : null,
|
|
1063
|
+
friends: account ? friendsPlaying(account.id) : [],
|
|
1064
|
+
others: state.accounts.map((other) => ({ username: other.username, playerId: other.playerId, isFriend: friendIds.has(other.id) })),
|
|
1065
|
+
});
|
|
1066
|
+
return markup === null ? reply(404, { error: { code: "not_found", message: "Nothing here." } }) : fragment(markup);
|
|
1067
|
+
}
|
|
1068
|
+
if (guideMatch && isPost) {
|
|
1069
|
+
const body = await readJson(request);
|
|
1070
|
+
if (!account) return reply(401, { error: { code: "not_signed_in", message: "Sign in first.", field: null, fix: "Sign in, then try again." } });
|
|
1071
|
+
if (guideMatch[1] === "sound") return reply(200, { sound: body });
|
|
1072
|
+
if (guideMatch[1] === "invite") return reply(200, { invite_status: "sent" });
|
|
985
1073
|
}
|
|
986
1074
|
if (request.method === "GET" && path === "/friends/among") {
|
|
987
1075
|
const given = (url.searchParams.get("player_ids") ?? "").split(",").filter(Boolean);
|
|
@@ -1114,7 +1202,8 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1114
1202
|
if (playerNumber) heardAtMs.set(playerNumber, now());
|
|
1115
1203
|
const roomCode = playerNumber ? roomOfPlayerId(playerIdOf(playerNumber)) : null;
|
|
1116
1204
|
if (roomCode) lastRoomCodes.set(playerNumber, roomCode);
|
|
1117
|
-
|
|
1205
|
+
const clipRequest = clipRequests.get(playerNumber);
|
|
1206
|
+
return reply(200, { reloadNumber, roomCode, openPlayerNumbers: openPlayerNumbers(), clipRequest: clipRequest ? { requestId: clipRequest.requestId, durationSec: clipRequest.durationSec } : null });
|
|
1118
1207
|
}
|
|
1119
1208
|
if (path === "/bench/claim" && request.method === "POST") {
|
|
1120
1209
|
const given = await readJson(request);
|
|
@@ -1124,6 +1213,39 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1124
1213
|
response.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8", "Cache-Control": "no-store" });
|
|
1125
1214
|
return response.end(ARRIVE_SCRIPT_SOURCE);
|
|
1126
1215
|
}
|
|
1216
|
+
// 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.
|
|
1217
|
+
if (path === "/bench/clips" && request.method === "POST") {
|
|
1218
|
+
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." } });
|
|
1219
|
+
const given = await readClipBody(request);
|
|
1220
|
+
const answer = await keepClip(given);
|
|
1221
|
+
const waiting = clipRequests.get(playerNumber);
|
|
1222
|
+
if (waiting && waiting.requestId === given.request_id) waiting.settle(answer);
|
|
1223
|
+
return reply(answer.error ? 400 : 201, answer);
|
|
1224
|
+
}
|
|
1225
|
+
const clipFileMatch = /^\/bench\/clip-files\/(clip-[0-9TZ-]+\.(mp4|jpg))$/.exec(path);
|
|
1226
|
+
if (clipFileMatch && request.method === "GET") {
|
|
1227
|
+
const file = join(localFolder, "clips", clipFileMatch[1]);
|
|
1228
|
+
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." } });
|
|
1229
|
+
response.writeHead(200, { "Content-Type": clipFileMatch[2] === "mp4" ? "video/mp4" : "image/jpeg", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" });
|
|
1230
|
+
return response.end(readFileSync(file));
|
|
1231
|
+
}
|
|
1232
|
+
// Send to Zaisma, from the bench's bar only: the clip and its still, with the bench's key, as zaisma clip sends them.
|
|
1233
|
+
if (path === "/bench/clips/send" && request.method === "POST") {
|
|
1234
|
+
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." } });
|
|
1235
|
+
const given = await readJson(request);
|
|
1236
|
+
const name = typeof given.clip_file === "string" && /^clip-[0-9TZ-]+\.mp4$/.test(given.clip_file) ? given.clip_file : null;
|
|
1237
|
+
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." } });
|
|
1238
|
+
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.` } });
|
|
1239
|
+
const sent = await fetch(`${developerApiUrl}/games/${gameSlug}/clip`, {
|
|
1240
|
+
method: "PUT",
|
|
1241
|
+
headers: { authorization: `Bearer ${zaismaKey}`, "content-type": "application/json", "x-zaisma-client": "bench" },
|
|
1242
|
+
body: JSON.stringify({ clip_base64: readFileSync(join(localFolder, "clips", name)).toString("base64"), still_base64: readFileSync(join(localFolder, "clips", name.replace(/\.mp4$/, ".jpg"))).toString("base64") }),
|
|
1243
|
+
}).catch(() => null);
|
|
1244
|
+
const answer = sent ? await sent.json().catch(() => null) : null;
|
|
1245
|
+
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." } });
|
|
1246
|
+
log(sent.ok ? `Clip sent to Zaisma: ${answer.review_message}` : `Zaisma refused the clip: ${answer.error?.message ?? sent.status}`);
|
|
1247
|
+
return reply(sent.status, answer);
|
|
1248
|
+
}
|
|
1127
1249
|
if (path === "/bench/leave" && request.method === "POST") {
|
|
1128
1250
|
heardAtMs.delete(playerNumber);
|
|
1129
1251
|
return reply(200, { isLeft: true });
|
|
@@ -1222,8 +1344,10 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1222
1344
|
return send(200, js, withSetup("__ZAISMA__", config, sdkText("zaisma.js")));
|
|
1223
1345
|
}
|
|
1224
1346
|
if (path === "_zaisma/v1.d.ts") return send(200, "text/plain; charset=utf-8", sdkText("zaisma.d.ts"));
|
|
1347
|
+
if (path === "_zaisma/clip.js") return send(200, js, clipScriptSource(benchOrigin));
|
|
1225
1348
|
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
1349
|
if (path === "_zaisma/picture.js") return send(200, js, withSetup("__ZAISMA_PICTURE__", { site: benchOrigin }, sdkText("picture.js")));
|
|
1350
|
+
if (path === "_zaisma/sound.js") return send(200, js, withSetup("__ZAISMA_SOUND__", { site: benchOrigin }, sdkText("sound.js")));
|
|
1227
1351
|
if (path === "_zaisma/saves.js") {
|
|
1228
1352
|
const versionId = url.searchParams.get("version_id");
|
|
1229
1353
|
return send(200, js, withSetup("__ZAISMA_SAVES__", { site: benchOrigin, saveLimitBytes: SAVE_LIMIT_BYTES, versionId: versionId === LOCAL_VERSION_ID ? versionId : null }, sdkText("saves.js")));
|
|
@@ -1248,7 +1372,7 @@ export async function startLocalPlay(givenOptions) {
|
|
|
1248
1372
|
const contentType = TYPES[extname(target).toLowerCase()] ?? "application/octet-stream";
|
|
1249
1373
|
const bytes = readFileSync(target);
|
|
1250
1374
|
if (contentType.startsWith("text/html")) {
|
|
1251
|
-
const injected = withScripts(bytes.toString("utf8"), [`/_zaisma/saves.js?v=${SCRIPTS_VERSION_NUMBER}&version_id=${LOCAL_VERSION_ID}`]);
|
|
1375
|
+
const injected = withScripts(bytes.toString("utf8"), [`/_zaisma/sound.js?v=${SCRIPTS_VERSION_NUMBER}`, `/_zaisma/saves.js?v=${SCRIPTS_VERSION_NUMBER}&version_id=${LOCAL_VERSION_ID}`, `/_zaisma/clip.js?v=${SCRIPTS_VERSION_NUMBER}`]);
|
|
1252
1376
|
return send(200, contentType, injected);
|
|
1253
1377
|
}
|
|
1254
1378
|
const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range ?? "");
|
package/package.json
CHANGED
package/sdk/sound.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Zaisma's own sound for every game. Zaisma adds this to every game page, first, before any of the game's own scripts: one volume and one mute
|
|
3
|
+
* over all of the game's audio, whatever the game does with its own settings, and voices (the SDK's room.voice) at a volume of their own. The
|
|
4
|
+
* player sets them in the guide's Settings, beside the game, and the Zaisma game page hands them over (zaisma:sound); nothing leaves the frame.
|
|
5
|
+
* Web Audio: whatever the game connects to a context's speakers goes through one gain of Zaisma's on its way. Audio and video elements: the volume
|
|
6
|
+
* a game sets is kept as its own, and the element plays at that times Zaisma's. Plain JavaScript, no dependencies, MIT licensed.
|
|
7
|
+
*/
|
|
8
|
+
(function () {
|
|
9
|
+
"use strict";
|
|
10
|
+
var site = typeof __ZAISMA_SOUND__ === "object" && __ZAISMA_SOUND__ ? __ZAISMA_SOUND__.site : "";
|
|
11
|
+
if (!site || window.parent === window || window.__zaismaSoundSet) return;
|
|
12
|
+
window.__zaismaSoundSet = true;
|
|
13
|
+
var sound = { gameVolumePct: 100, isGameSoundOn: true, voiceVolumePct: 100 };
|
|
14
|
+
var levelOf = function (isVoice) { return isVoice ? sound.voiceVolumePct / 100 : sound.isGameSoundOn ? sound.gameVolumePct / 100 : 0; };
|
|
15
|
+
|
|
16
|
+
/* ---- Web Audio ---- */
|
|
17
|
+
|
|
18
|
+
var Node = window.AudioNode, Destination = window.AudioDestinationNode;
|
|
19
|
+
var gains = [];
|
|
20
|
+
if (Node && Destination) {
|
|
21
|
+
var connect = Node.prototype.connect, disconnect = Node.prototype.disconnect;
|
|
22
|
+
// Each context's own gain in front of its speakers, made the first time something is connected to them.
|
|
23
|
+
var gainOf = function (audioContext) {
|
|
24
|
+
if (audioContext.__zaismaGain) return audioContext.__zaismaGain;
|
|
25
|
+
var gain = audioContext.createGain();
|
|
26
|
+
connect.call(gain, audioContext.destination);
|
|
27
|
+
gain.gain.value = levelOf(audioContext.__zaismaVoice === true);
|
|
28
|
+
audioContext.__zaismaGain = gain;
|
|
29
|
+
gains.push({ audioContext: audioContext, gain: gain });
|
|
30
|
+
return gain;
|
|
31
|
+
};
|
|
32
|
+
Node.prototype.connect = function (target) {
|
|
33
|
+
if (target instanceof Destination && this !== target.context.__zaismaGain) {
|
|
34
|
+
var rest = Array.prototype.slice.call(arguments, 1);
|
|
35
|
+
return connect.apply(this, [gainOf(target.context)].concat(rest));
|
|
36
|
+
}
|
|
37
|
+
return connect.apply(this, arguments);
|
|
38
|
+
};
|
|
39
|
+
Node.prototype.disconnect = function (target) {
|
|
40
|
+
if (target instanceof Destination && target.context.__zaismaGain && this !== target.context.__zaismaGain) {
|
|
41
|
+
var rest = Array.prototype.slice.call(arguments, 1);
|
|
42
|
+
return disconnect.apply(this, [target.context.__zaismaGain].concat(rest));
|
|
43
|
+
}
|
|
44
|
+
return disconnect.apply(this, arguments);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/* ---- Audio and video elements ---- */
|
|
49
|
+
|
|
50
|
+
var Media = window.HTMLMediaElement;
|
|
51
|
+
var elements = [];
|
|
52
|
+
var volume = Media && Object.getOwnPropertyDescriptor(Media.prototype, "volume");
|
|
53
|
+
if (volume && volume.get && volume.set) {
|
|
54
|
+
var own = function (element) { return typeof element.__zaismaVolume === "number" ? element.__zaismaVolume : 1; };
|
|
55
|
+
var apply = function (element) { volume.set.call(element, Math.max(0, Math.min(1, own(element) * levelOf(element.__zaismaVoice === true)))); };
|
|
56
|
+
var keep = function (element) { if (element.__zaismaKept) return; element.__zaismaKept = true; elements.push(new WeakRef(element)); };
|
|
57
|
+
Object.defineProperty(Media.prototype, "volume", {
|
|
58
|
+
configurable: true,
|
|
59
|
+
enumerable: volume.enumerable,
|
|
60
|
+
get: function () { return own(this); },
|
|
61
|
+
set: function (volumeLevel) { this.__zaismaVolume = Math.max(0, Math.min(1, Number(volumeLevel))); keep(this); apply(this); },
|
|
62
|
+
});
|
|
63
|
+
var play = Media.prototype.play;
|
|
64
|
+
Media.prototype.play = function () { keep(this); apply(this); return play.apply(this, arguments); };
|
|
65
|
+
document.addEventListener("play", function (event) { if (event.target instanceof Media) { keep(event.target); apply(event.target); } }, true);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function applyAll() {
|
|
69
|
+
gains.forEach(function (each) {
|
|
70
|
+
var level = levelOf(each.audioContext.__zaismaVoice === true);
|
|
71
|
+
try { each.gain.gain.setTargetAtTime(level, each.audioContext.currentTime, 0.02); } catch (error) { each.gain.gain.value = level; }
|
|
72
|
+
});
|
|
73
|
+
elements = elements.filter(function (held) { var element = held.deref(); if (element) apply(element); return Boolean(element); });
|
|
74
|
+
}
|
|
75
|
+
var pct = function (given, fallback) { return typeof given === "number" && given >= 0 && given <= 100 ? Math.round(given) : fallback; };
|
|
76
|
+
window.addEventListener("message", function (event) {
|
|
77
|
+
var told = event.data;
|
|
78
|
+
if (event.origin !== site || event.source !== window.parent || !told || told.type !== "zaisma:sound") return;
|
|
79
|
+
sound = { gameVolumePct: pct(told.gameVolumePct, 100), isGameSoundOn: told.isGameSoundOn !== false, voiceVolumePct: pct(told.voiceVolumePct, 100) };
|
|
80
|
+
applyAll();
|
|
81
|
+
});
|
|
82
|
+
// Asked for as the game starts, so a game that plays at once plays at the player's volume.
|
|
83
|
+
window.parent.postMessage({ type: "zaisma:sound-request" }, site);
|
|
84
|
+
})();
|
package/sdk/zaisma.d.ts
CHANGED
|
@@ -209,7 +209,7 @@ declare namespace Zaisma {
|
|
|
209
209
|
const server: Server;
|
|
210
210
|
|
|
211
211
|
/**
|
|
212
|
-
* Invite friends. On Zaisma it opens Zaisma's invite sheet, the same as the
|
|
212
|
+
* Invite friends. On Zaisma it opens Zaisma's invite sheet, the same as the guide's Share: the
|
|
213
213
|
* room's QR code, link and code, Copy and the share sheet ("opened", or "failed" when the page couldn't
|
|
214
214
|
* open it). On your own site it opens the share sheet on phones, otherwise copies the room's invite link
|
|
215
215
|
* (the game's page without a room). Call it from a button in your game, like on a "waiting for players"
|
|
@@ -606,7 +606,7 @@ declare namespace Zaisma {
|
|
|
606
606
|
|
|
607
607
|
/**
|
|
608
608
|
* Whether Zaisma's page covers the game right now, so a game can pause or hold the player's input while it does.
|
|
609
|
-
* coveredBy is "sheet" while one of Zaisma's sheets is open over the game (buying, the
|
|
609
|
+
* coveredBy is "sheet" while one of Zaisma's sheets is open over the game (buying, the guide, Report: the player is
|
|
610
610
|
* busy with it), "card" while one of its cards is over the game's corner (Still there?, Keep your progress; the
|
|
611
611
|
* game stays in view and playable), and null otherwise. Always null outside Zaisma's page (your own site, a
|
|
612
612
|
* local test). Listen for "coveredBy" to hear each change.
|
|
@@ -618,10 +618,26 @@ declare namespace Zaisma {
|
|
|
618
618
|
*/
|
|
619
619
|
const page: Page;
|
|
620
620
|
|
|
621
|
-
/** Whether Zaisma's page covers the game ({@link page}). */
|
|
621
|
+
/** Whether Zaisma's page covers the game ({@link page}), and the game's two calls on it. */
|
|
622
622
|
interface Page {
|
|
623
623
|
/** "sheet", "card" or null: what of Zaisma's is over the game now. Read-only. */
|
|
624
624
|
readonly coveredBy: CoveredBy;
|
|
625
|
+
/**
|
|
626
|
+
* Opens Zaisma's player card for a player in the game's room, on that player's press in your game (a Card button on a scoreboard): who they are, how
|
|
627
|
+
* the player knows them, Add friend, Mute, Block and Report. Only a player in the room the game is in; the guide beside the game shows it. It opens
|
|
628
|
+
* only right after the player's own press, as Zaisma.invite does: called at any other time, nothing opens.
|
|
629
|
+
* Fails with error.code "bad_player_id" for something that isn't a player's id, and "not_on_zaisma" off Zaisma's page.
|
|
630
|
+
* @example
|
|
631
|
+
* cardButton.onclick = () => Zaisma.page.openPlayerCard(player.id);
|
|
632
|
+
*/
|
|
633
|
+
openPlayerCard(playerId: string): Promise<void>;
|
|
634
|
+
/**
|
|
635
|
+
* Ends play from the game's own menu, after its own confirm: the player lands on the game's page, where the guide's Leave lands. Fails with
|
|
636
|
+
* error.code "not_on_zaisma" off Zaisma's page, where the game ends play its own way.
|
|
637
|
+
* @example
|
|
638
|
+
* quitConfirm.onclick = () => Zaisma.page.leave();
|
|
639
|
+
*/
|
|
640
|
+
leave(): Promise<void>;
|
|
625
641
|
/** Listen for "coveredBy": called with the new value each time it changes. A wrong name fails with error.code "unknown_event". */
|
|
626
642
|
on(event: "coveredBy", listener: (coveredBy: CoveredBy) => void): Page;
|
|
627
643
|
off(event: "coveredBy", listener: (coveredBy: CoveredBy) => void): Page;
|
package/sdk/zaisma.js
CHANGED
|
@@ -1982,13 +1982,15 @@
|
|
|
1982
1982
|
this._isMicrophoneMuted = Boolean(voiceOptions && voiceOptions.isMuted);
|
|
1983
1983
|
this._wantsJoin = true;
|
|
1984
1984
|
// Made and woken here, inside the player's tap: made later, after the microphone's prompt, browsers keep it silent.
|
|
1985
|
-
|
|
1985
|
+
// Voices are marked as such, so Zaisma's own sound (_zaisma/sound.js) plays them at the player's voice volume, apart from the game's.
|
|
1986
|
+
if (!this.audioContext) { this.audioContext = new AudioContext(); this.audioContext.__zaismaVoice = true; }
|
|
1986
1987
|
if (!this.outputNode) {
|
|
1987
1988
|
// Voices reach the speakers through a media element, not the context's own output: echo cancellation hears what
|
|
1988
1989
|
// media elements play (on phones, only that), so the microphone doesn't send the voices back. The game's own sound
|
|
1989
1990
|
// can come this way too (outputNode).
|
|
1990
1991
|
var output = this.audioContext.createMediaStreamDestination();
|
|
1991
1992
|
this._outputElement = new Audio();
|
|
1993
|
+
this._outputElement.__zaismaVoice = true;
|
|
1992
1994
|
this._outputElement.srcObject = output.stream;
|
|
1993
1995
|
this.outputNode = output;
|
|
1994
1996
|
this._unlockSoundOnTap();
|
|
@@ -2104,6 +2106,7 @@
|
|
|
2104
2106
|
var stream = new MediaStream([transceiver.receiver.track]);
|
|
2105
2107
|
// Chrome plays a remote voice into Web Audio only while a media element holds it too; the element itself stays silent.
|
|
2106
2108
|
var element = new Audio();
|
|
2109
|
+
element.__zaismaVoice = true;
|
|
2107
2110
|
element.muted = true;
|
|
2108
2111
|
element.srcObject = stream;
|
|
2109
2112
|
element.play().catch(function () {});
|
|
@@ -3040,7 +3043,26 @@
|
|
|
3040
3043
|
*/
|
|
3041
3044
|
var pageEvents = new Emitter(PAGE_EVENTS, "Zaisma.page has");
|
|
3042
3045
|
var coveredBy = null;
|
|
3046
|
+
/*
|
|
3047
|
+
* The game's two calls on Zaisma's page (zaisma.d.ts: Zaisma.page.openPlayerCard, Zaisma.page.leave). A game owns everything inside itself, so its own
|
|
3048
|
+
* scoreboard's Card button and its own menu's Leave are its; Zaisma only draws the card (with Block and Report always in it) and takes the player out.
|
|
3049
|
+
* Off Zaisma (the developer's own site, a local test without a page) there's no page to answer: each says so, and the game does what it does there.
|
|
3050
|
+
*/
|
|
3051
|
+
var MAXIMUM_PLAYER_ID_CHARACTER_COUNT = 60;
|
|
3052
|
+
function openPlayerCard(playerId) {
|
|
3053
|
+
if (typeof playerId !== "string" || !playerId || playerId.length > MAXIMUM_PLAYER_ID_CHARACTER_COUNT) return Promise.reject(codedError("bad_player_id", "openPlayerCard takes the player's id, as room.players lists it."));
|
|
3054
|
+
if (!config.site || window.parent === window) return Promise.reject(notOnZaisma("Zaisma's player card opens when the game is played on its zaisma.com page."));
|
|
3055
|
+
window.parent.postMessage({ type: "zaisma:open-player-card", playerId: playerId }, config.site);
|
|
3056
|
+
return Promise.resolve();
|
|
3057
|
+
}
|
|
3058
|
+
function leave() {
|
|
3059
|
+
if (!config.site || window.parent === window) return Promise.reject(notOnZaisma("Leaving through Zaisma works when the game is played on its zaisma.com page."));
|
|
3060
|
+
window.parent.postMessage({ type: "zaisma:leave" }, config.site);
|
|
3061
|
+
return Promise.resolve();
|
|
3062
|
+
}
|
|
3043
3063
|
var zaismaPage = {
|
|
3064
|
+
openPlayerCard: openPlayerCard,
|
|
3065
|
+
leave: leave,
|
|
3044
3066
|
on: function (event, listener) {
|
|
3045
3067
|
pageEvents.on(event, listener);
|
|
3046
3068
|
return zaismaPage;
|
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
|
+
};
|