/** * SAB F1 UI - broadcast output relay. * * A tiny WebSocket relay that lets the controller app (the broadcast/workspaces * UI) push its graphics state to one or more independent output pages, e.g. an * OBS browser source running http://localhost:3000/output. * * Run with: npm run relay (or: node server/relayServer.js) * * Clients connect to ws://:/?role=controller|output * Protocol (JSON): * controller -> relay : { "type": "hello", "role": "controller" } * { "type": "state", "payload": { ...redux slices... } } * relay -> output : { "type": "welcome", "role": "output", ... } * { "type": "state", "payload": { ... } } * The relay caches the last state, so a browser source that (re)connects always * gets a picture immediately, even if the controller is idle. */ const http = require("http"); const { WebSocketServer } = require("ws"); const PORT = Number(process.env.RELAY_PORT || 8181); const HOST = process.env.RELAY_HOST || "0.0.0.0"; let lastState = null; let controllerCount = 0; let outputCount = 0; function log(...args) { console.log("[relay " + new Date().toISOString() + "]", ...args); } const server = http.createServer((req, res) => { res.setHeader("access-control-allow-origin", "*"); if (req.url && req.url.split("?")[0] === "/health") { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ ok: true, controllers: controllerCount, outputs: outputCount, hasState: lastState != null, })); return; } res.writeHead(200, { "content-type": "text/plain" }); res.end( "sab-f1-ui broadcast relay\n" + "ws://:" + PORT + "/?role=controller|output\n" + "health: http://:" + PORT + "/health\n", ); }); const wss = new WebSocketServer({ server }); function send(ws, message) { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(message)); } wss.on("connection", (ws, req) => { const requestUrl = new URL(req.url || "/", "http://localhost"); ws.role = requestUrl.searchParams.get("role") === "controller" ? "controller" : "output"; ws.isAlive = true; if (ws.role === "controller") controllerCount += 1; else outputCount += 1; log(ws.role + " connected from " + (req.socket.remoteAddress || "?") + " (" + controllerCount + " controllers, " + outputCount + " outputs)"); send(ws, { type: "welcome", role: ws.role, controllers: controllerCount, outputs: outputCount }); // A freshly connected output gets the current picture right away. if (ws.role === "output" && lastState != null) send(ws, lastState); ws.on("message", (raw) => { let message; try { message = JSON.parse(raw.toString()); } catch (error) { return; } if (message == null || typeof message !== "object") return; if (message.type === "hello") { send(ws, { type: "welcome", role: ws.role, controllers: controllerCount, outputs: outputCount }); return; } if (message.type === "state") { // Only a controller may drive the output. if (ws.role !== "controller") return; /** * Cache the *merged* picture, not just this patch. * * The controller sends incremental patches (only the slices whose * reference changed), so caching the raw message meant an output that * connected later - OBS refreshing a browser source when its scene * becomes active, or any reconnect - received only whichever slices * happened to change in the very last transition. It would render the * timing tower but no chyron, or the reverse, until the controller * touched the missing slice again. */ lastState = { type: "state", payload: Object.assign({}, lastState && lastState.payload, message.payload), }; // Live outputs still get the small patch; they merge it themselves. const data = JSON.stringify(message); wss.clients.forEach((client) => { if (client !== ws && client.role === "output" && client.readyState === client.OPEN) { client.send(data); } }); return; } if (message.type === "ping") { send(ws, { type: "pong" }); } }); ws.on("pong", () => { ws.isAlive = true; }); ws.on("close", () => { if (ws.role === "controller") controllerCount -= 1; else outputCount -= 1; log(ws.role + " disconnected (" + controllerCount + " controllers, " + outputCount + " outputs)"); }); ws.on("error", (error) => log(ws.role + " error: " + error.message)); }); const heartbeat = setInterval(() => { wss.clients.forEach((ws) => { if (ws.isAlive === false) { ws.terminate(); return; } ws.isAlive = false; try { ws.ping(); } catch (error) { // Ignore, the close handler will clean up. } }); }, 30000); wss.on("close", () => clearInterval(heartbeat)); server.listen(PORT, HOST, () => { log("relay listening on ws://" + HOST + ":" + PORT + " (health http://" + HOST + ":" + PORT + "/health)"); });