/** * Bridge between the browser editor and a real Pure Data. * * browser --WebSocket--> bridge --UDP/FUDI--> Pd * ^ | * +------ UDP/FUDI ------+ * * Pd talks to us with `netreceive -u 8091` / `netsend -u localhost 8091`, and * we talk to it on the patch's own receiver (`netreceive -u 8081`). * * node server/bridge.mjs [--port 8090] [--to-pd 8081] [--from-pd 8091] * [--pd /usr/bin/pd] [--silent] */ import { spawn } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import dgram from "node:dgram"; import { WebSocketServer } from "ws"; const HERE = dirname(fileURLToPath(import.meta.url)); function arg(name, fallback) { const i = process.argv.indexOf(`--${name}`); return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback; } const flag = (name) => process.argv.includes(`--${name}`); const PORT = Number(arg("port", 8090)); const TO_PD = Number(arg("to-pd", 8081)); const FROM_PD = Number(arg("from-pd", 8091)); const PD_BIN = arg("pd", "pd"); const SILENT = flag("silent"); const PATCH_DIR = resolve(arg("dir", join(HERE, "patches"))); mkdirSync(PATCH_DIR, { recursive: true }); // --- FUDI ------------------------------------------------------------------ /** Parse `a b c;` into atoms. Pd escapes `;, \$` with a backslash. */ function parseFudi(buffer) { const messages = []; for (const record of buffer.toString("utf8").split(";")) { if (!record.trim()) continue; const atoms = []; let buf = ""; for (let i = 0; i < record.length; i++) { const c = record[i]; if (c === "\\") { buf += record[++i] ?? ""; continue; } if (c === " " || c === "\n" || c === "\r" || c === "\t") { if (buf) atoms.push(buf); buf = ""; continue; } buf += c; } if (buf) atoms.push(buf); if (atoms.length) messages.push({ receiver: atoms[0], args: atoms.slice(1) }); } return messages; } /** Atoms that need no escaping, and numbers, go out bare. */ function quoteAtom(atom) { const s = String(atom); if (/^-?\d+(\.\d+)?$/.test(s)) return s; return s.replace(/([\\;,])/g, "\\$1"); } function formatFudi(receiver, args) { return `${[receiver, ...args].map(quoteAtom).join(" ")};\n`; } // --- state ----------------------------------------------------------------- const udpToPd = dgram.createSocket("udp4"); const udpFromPd = dgram.createSocket("udp4"); const wss = new WebSocketServer({ port: PORT }); let pd = null; let pdFile = null; const logRing = []; const MAX_LOG = 400; function broadcast(message) { const data = JSON.stringify(message); for (const client of wss.clients) { if (client.readyState === 1) client.send(data); } } function log(stream, line) { const entry = { type: "log", stream, line }; logRing.push(entry); if (logRing.length > MAX_LOG) logRing.shift(); broadcast(entry); } function stopPd() { if (!pd) return; const child = pd; pd = null; child.kill("SIGTERM"); } function startPd(file) { stopPd(); const args = ["-nogui", "-open", file]; if (SILENT) args.push("-nosound"); const child = spawn(PD_BIN, args, { stdio: ["ignore", "pipe", "pipe"] }); pd = child; pdFile = file; log("stderr", `$ ${PD_BIN} ${args.join(" ")}`); const pipe = (stream) => (chunk) => { for (const line of String(chunk).split("\n")) { if (line.trim()) log(stream, line); } }; child.stdout.on("data", pipe("stdout")); child.stderr.on("data", pipe("stderr")); child.on("exit", (code) => { if (pd === child) { pd = null; pdFile = null; } log("stderr", `pd exited with code ${code}`); broadcast({ type: "pd-status", running: false, file: null }); }); child.on("error", (err) => log("stderr", `failed to start pd: ${err.message}`)); broadcast({ type: "pd-status", running: true, file }); } // --- sockets --------------------------------------------------------------- udpFromPd.on("message", (msg) => { for (const { receiver, args } of parseFudi(msg)) { broadcast({ type: "from-pd", receiver, args }); } }); udpFromPd.bind(FROM_PD, "127.0.0.1"); wss.on("connection", (socket) => { socket.send( JSON.stringify({ type: "hello", pdRunning: Boolean(pd), toPdPort: TO_PD, fromPdPort: FROM_PD, }), ); for (const entry of logRing) socket.send(JSON.stringify(entry)); socket.on("message", (data) => { let message; try { message = JSON.parse(String(data)); } catch { return; } switch (message.type) { case "send": { const text = formatFudi(message.receiver, message.args ?? []); udpToPd.send(text, TO_PD, "127.0.0.1"); break; } case "raw": { udpToPd.send(`${message.message};\n`, TO_PD, "127.0.0.1"); break; } case "save": { // Keep the name a leaf: the browser must not write outside patches/. const name = String(message.name || "patch.pd").replace(/[^\w.-]/g, "_"); const file = join(PATCH_DIR, name.endsWith(".pd") ? name : `${name}.pd`); writeFileSync(file, String(message.text)); log("stderr", `saved ${file}`); socket.send(JSON.stringify({ type: "saved", file })); break; } case "run": { const name = String(message.file || "").replace(/[^\w.-]/g, "_"); const file = join(PATCH_DIR, name); startPd(file); break; } case "stop": stopPd(); broadcast({ type: "pd-status", running: false, file: null }); break; default: socket.send(JSON.stringify({ type: "error", message: `unknown message ${message.type}` })); } }); }); console.log(`dragology-pd bridge`); console.log(` browser ws://127.0.0.1:${PORT}`); console.log(` -> pd udp 127.0.0.1:${TO_PD}`); console.log(` <- pd udp 127.0.0.1:${FROM_PD}`); console.log(` patches ${PATCH_DIR}`); for (const signal of ["SIGINT", "SIGTERM"]) { process.on(signal, () => { stopPd(); process.exit(0); }); }